# Type The UseState Hook With NULL Initial Value In React

If you don’t know how to type the useState hook with NULL initial value in React, don’t worry. We will give you some solutions in this article. Read on it.

## Initial state value of useState

• It is a basic hook of reactjs version > 16.8.
• Help us be able to use state in functional components.
• Input: initialState (value or function).
• Output: an array with 2 elements for state and setState, respectively.

Syntax:

const [state, setState] = useState(initialStateValue)

Parameter:

• state: defines the name of the state. It can be a single value or an object (as a parameter of useState).
• setState: defines the function name used to update the state (as a parameter of useState).
• initial state value: is the initial value of the state.

The initial state is only used for the first time. Later it is not used anymore.

## Type the UseState hook with NULL initial value in React

### Set a null string, number

You can set the useState hook’s initialization value to null to make the program more explicit. The code below will show you a simple example of converting a state from null to string.

Code:

import React, { useState } from "react";

const App = () => {
const [text, setText] = useState(null);
return (
<div>
<h2>LearnShareIT</h2>
<p>{text}</p>
<button onClick={() => setText("Hello World!!")}>Show text</button>
</div>
);
};

export default App;

Output:

When you select the show text button, the state will be reset from the initial null value and will be reset to “Hello World!!!” and rendered to the web page.

### Set a null object

And this will be a more familiar example in practice when you need to initialize a useState as an object. Because when the object has not been reset to the state, we still have to get its key: value pairs to process the logic, so what do we do in this case? Take a look at the example below.

Code:

import React, { useState } from "react";

const App = () => {
const [object, setObject] = useState({ name: null, age: null });
return (
<div>
<h2>LearnShareIT</h2>
<p>{object.name == null ? "Empty" : JSON.stringify(object)}</p>
<button onClick={() => setObject({ name: "John", age: 28 })}>
Show text
</button>
</div>
);
};

export default App;

Output:

So when the component is mounted, the value of the key names in the object is set to null by default so that the text will return “Empty”. When pressing the Show button, the program resets it to a new object and renders it to the screen. I hope it is helpful to you.

## Summary

To summarize, there are many ways to type the useState hook with NULL initial value in React. After reading this article, we know some simple ways, like setting a null string or number or setting a null object in React.

Maybe you are interested: