React useState

`useState` lets a React function component keep local state between renders. It returns the current state value and a setter that requests an update when the state changes.

Call `useState` at the top level of a function component or custom Hook to create a state variable. You provide an initial value, and React returns an array containing the current value and a setter function.

Calling the setter does not immediately replace the value in the currently executing function. Instead, it requests another render, during which the component receives the updated state. React may batch multiple state updates before rendering.

When the next state depends on the previous state, use the updater form such as `setCount(c => c + 1)`. This avoids relying on a potentially stale value captured by the current render.

State should be treated as immutable from the component's perspective. For objects and arrays, create a new value when updating rather than modifying the existing state object directly.

Key points

Interview questions

How should you update an object stored with `useState`?

Create a new object containing the changed fields instead of mutating the existing object. The spread syntax is commonly used, such as `setUser(prev => ({ ...prev, name: "Sam" }))`. Replacing the object gives React a new state value and preserves unrelated fields. The same principle applies to arrays.

What does `useState` return?

It returns an array containing the current state value and a setter function. The setter is used to request a state update. A common pattern is `const [count, setCount] = useState(0)`. On a later render, `count` reflects the updated state.

Why can state appear not to update immediately after calling its setter?

A state setter requests an update rather than changing the value held by the current render. The current function continues using the state value from that render. React can also batch updates before rendering again. The updated value is available during the subsequent render.

When should you use a functional state update?

Use a functional update when the next state is calculated from the previous state. For example, `setCount(c => c + 1)` receives the latest queued state value. This is particularly important when multiple updates are made before React renders again. It makes the dependency on the previous state explicit.