Fundamentalsbeginner

State Basics with useState

Understand how component-local state works, how updates trigger re-renders, and common pitfalls with the useState hook.

State is data that a component owns and that can change over time, causing the component to re-render when it does. The useState hook is the primary way function components declare state: it returns a pair — the current value and a setter function — and calling the setter schedules a re-render with the new value.

State is like a sticky note pad on a specific component's desk — every re-render, React hands the component back the same pad with whatever was last written on it, not a fresh blank one.

Key Concepts

1
Unlike props, state is private to the component that declares it (unless explicitly passed down). Each call to useState creates an independent piece of state, and React preserves that state across re-renders as long as the component stays mounted in the same position in the tree.
useState
2
A common point of confusion is that state updates are not synchronous and not immediately reflected in the current render's closure. Calling the setter doesn't mutate the variable in place; it tells React to re-render with a new value on the next pass. This is why reading state right after calling its setter still shows the old value within the same function execution.
3
Interviewers commonly probe whether candidates understand batching, why functional updates (setCount(c => c + 1)) are safer than value-based updates, and how state resets when a component's key changes or it unmounts.
setCount(c => c + 1)