DEV Community

Aftab
Aftab

Posted on

useState in React

Image description

useState is a Hook that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.

What does the React.useState Hook do?

useState enables you to add state to function components. Calling React.useState inside a function component generates a single piece of state associated with that component.

Whereas the state in a class is always an object, with Hooks, the state can be any type. Each piece of state holds a single value, which can be an object, an array, a boolean, or any other type you can imagine.

So when should you use the useState Hook? It’s especially useful for local component state, but larger projects might require additional state management solutions.

Declaring state in React
useState is a named export from react. To use it, you can write:

Image description

Or to import it just write useState:

Image description

The useState Hook allows you to declare only one state variable (of any type) at a time, like this:

Image description

Using useState alone won’t work because its argument is used the first time only — not every time the property changes (look here for the right way to do this).

But useState doesn’t return just a variable as the previous examples imply.

It returns an array, where the first element is the state variable and the second element is a function to update the value of the variable:

Image description

Usually, you’ll use array destructuring to simplify the code shown above:

Image description

This way, you can use the state variable in the functional component like any other variable:

Image description

But why does useState return array?

Because compared to an object, an array is more flexible and easy to use.

If the method returned an object with a fixed set of properties, you wouldn’t be able to assign custom names in an easy way.

You’d have to do something like this (assuming the properties of the object are state and setState):

Image description

Top comments (0)