useState Hook

React’s useState hook is used to keep the state in the functional component. It is similar to this.setState in the class component. The state is preserved every time the component is re-render.

The useState hook takes only one argument which is the initial state and returns two values:

You can store any values with the format of strings, numbers, booleans, arrays, objects.

  • The value of the state.
  • The setter function of the state.

Functional way to compute complex initial state

Sometimes, you may need to do some computation for the initial state and useState hook do accept a function as the argument and take the return value from the function as the initial state. The function is guaranteed to run only once.

Functional way of setting state

One of the common pitfalls of using useState is the problem of a stale state. The stale state normally happens when we try to update the state in a closure.

As state updating is an asynchronous process, re-rendering may not happen immediately after we change the state. Thus, if the closure is being triggered before the state update occurred, it can cause the closure is still using the old value stored when the closure is defined instead of the updated value.

One simple solution to avoid the stale state problem is by using the functional way of setting the state. We can pass a closure as the argument to the useState. In the closure, we can reliably get the updated state as the parameters and returns the new state.

Exit mobile version