Overview
TheuseState hook allows functional components to have state. It returns the current state value and a function to update it.
Signature
Parameters
The initial state value. If a function is provided, it will be called to compute the initial state (lazy initialization).
Returns
The current state value.
A function to update the state. Accepts either a new value or a function that receives the previous state and returns the new state.Signature:
setState(newState | ((prevState) => newState))Behavior:- Only triggers re-render if the new state is different from the current state (using
!==comparison) - Accepts a function for updates based on previous state
- Warns if called on unmounted components
Usage Examples
Basic State
Functional Updates
Use a function when the new state depends on the previous state:Lazy Initialization
Use a function to compute expensive initial state only once:Object State
Rules and Behavior
- Must be called at the top level - Don’t call
useStateinside loops, conditions, or nested functions - Only in functional components - Cannot be used in class components
- State updates trigger re-renders - The component re-renders when state changes
- Strict equality check - Re-render only occurs if
newState !== currentState - Safe updates - Warns if attempting to update state on unmounted components
- Preserves identity - The
setStatefunction has a stable identity and won’t change between re-renders
Implementation Details
- Uses a global hook index to track which hook is being called
- Stores state in a WeakMap keyed by component instance
- Supports functional state updates for computing new state from previous state
- Performs shallow comparison (
!==) to determine if re-render is needed