Skip to main content
useState returns a stateful value and a function to update it. The state persists between renders and updating it triggers a re-render of the component.

Signature

Parameters

S | (() => S)
The initial value for the state, or a function that returns the initial value. If a function is provided, it will only be executed during the initial render (lazy initialization).

Returns

Returns a tuple containing:
  1. Current state value (S): The current state value
  2. State setter function (Dispatch<StateUpdater<S>>): A function to update the state. Can accept either:
    • A new state value directly
    • A function that receives the previous state and returns the new state

Basic Usage

Lazy Initialization

If computing the initial state is expensive, you can pass a function that will only be called during the initial render:

Functional Updates

When the new state depends on the previous state, use the functional form of the setter:

Multiple State Variables

Object State

State updates may be batched for performance. Multiple setState calls in the same event handler are batched together, resulting in a single re-render.
If you call the state setter with the same value as the current state (compared using Object.is), Preact will skip re-rendering the component and its children.