Skip to main content
useState is a React Hook that lets you add a state variable to your component.

Parameters

S | (() => S)
required
The initial value of the state. It can be a value of any type, but there is special behavior for functions.
  • If you pass a function as initialState, it will be treated as an initializer function. It should be pure, take no arguments, and return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state.
This parameter is ignored after the initial render.

Returns

useState returns an array with exactly two values:
S
The current state. During the first render, it will match the initialState you passed.
Dispatch<BasicStateAction<S>>
The set function that lets you update the state to a different value and trigger a re-render.The set function accepts either:
  • A new state value directly: setState(newValue)
  • An updater function: setState(prev => prev + 1)
The set function has no return value.

Usage

Adding state to a component

Call useState at the top level of your component to declare a state variable:

Updating state based on previous state

When the new state is calculated from the previous state, pass an updater function:
Without an updater function, multiple state updates in the same event handler might not work as expected:
This happens because count doesn’t change until the next render, so each setCount(count + 1) call becomes setCount(1).

Updating objects and arrays in state

You must create new objects/arrays rather than mutating existing ones:

Using the initializer function

If the initial state is expensive to compute, pass a function:
React only calls the initializer function during initialization. The function’s return value is stored as the initial state and isn’t called on subsequent renders.

Resetting state with a key

You can reset a component’s state by changing its key:

TypeScript

Basic types

Nullable types

With initializer function

Troubleshooting

My state updates but the component doesn’t re-render

If you mutate state directly, React won’t detect the change:

My state shows the old value right after updating

State updates are asynchronous and don’t take effect until the next render:

I’m getting “Too many re-renders” error

This happens when you call a state setter during render:
Move the state update to an event handler or useEffect:

My initializer function runs on every render

Make sure you’re passing the function itself, not calling it:

Common Patterns

Toggle boolean state

State derived from props