foundation
useState
Store local component state, use functional updates, and understand batching and stale closures.
`useState` returns a value and a setter. The initial argument is used only on first mount unless you pass an initializer function for expensive setup. Setters accept the next value or an updater function.
In event handlers React 18 batches state updates, so multiple setters in one handler produce one rerender. Closures in async callbacks may see stale state — functional updaters or refs solve that. Do not call hooks conditionally.
const [count, setCount] = useState(() => computeInitial());
function increment() {
setCount((c) => c + 1);
}
On interviews, explain the concept with a concrete example and name the behavior interviewers probe.
Common pitfalls include hiding data flow, over-splitting components, and putting side effects in render.
The trade-off is often clarity versus reuse or explicit props versus convenience.
Checklist:
- Use functional updates when next state depends on previous.
- Lazy init for costly first value.
- Hooks run in the same order every render.