useState

Adds a piece of local state to a function component.

Since React 16.8 Spec ↗

Syntax

const [state, setState] = useState(initialState)

Parameters

NameTypeRequiredDescription
initialState any | function Yes The initial state value, or a lazy initializer function called once on mount.

Returns

array — A pair: the current state value and a setter function to update it.

Examples

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(c => c + 1)}>
      {count}
    </button>
  );
}
const [user, setUser] = useState(() => loadUser());

Notes

Call hooks only at the top level of a component, never in loops or conditions. Pass an updater function when the next state depends on the previous value. The setter replaces state; it does not merge objects. Setting state to the same value (Object.is) bails out of a re-render.

See also