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.
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)
Usage
Adding state to a component
CalluseState 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:Updating objects and arrays in state
You must create new objects/arrays rather than mutating existing ones:- Objects
- Arrays
- Nested Objects
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 itskey: