useState State Hook
Last updated: 2026-11-02
useState State Hook
useState adds a state variable to a function component: it returns the current value and a setter, and any change re-renders the component. All interaction-driven UI data — inputs, toggles, counters — is managed by it.
| Group | Rendering & State |
|---|---|
| Kind | Hook |
| Since | React 16.8 |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
const [count, setCount] = useState(0)
// ↑ current ↑ setter ↑ initial value (first render only)
⚙️ Parameters
| initialState | Initial state. Used as the current value on the first render only; ignored afterwards. |
|---|---|
| setCount (setter) | The setter: pass a new value or an updater function based on the previous value; calling it schedules a re-render. |
Returns:Returns a two-element array: [current value, setter]. Usually destructured with custom names; setters start with "set" by convention.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
A centered heading "Current count: 0" with three buttons. +1 increments, -1 decrements, Reset returns to 0.
💡 Key Points
💡 Tip Name setters with a set prefix (setCount / setOpen) so intent is obvious at a glance.
⚠️ Warning Mutating the state variable directly (count = 5) does NOT re-render — always call the setter.
ℹ️ Info The initial value applies on the first render only; changing that expression later never resets the state.
🏷️ More Rendering & State
💡 Related Cases
More case studies coming soon.
📚 Related Tutorials
❓ FAQ
Q Why does printing state right after the change still show the old value?
A setCount schedules the next render; it does not assign immediately. The count in the current closure stays stale — compute from the previous value inside the updater.
Q Can the initial value of useState be a function?
A Yes. Passing a function means lazy initialization — called once on the first render, ideal when the initial value is expensive to compute.
Q Can a component use useState more than once?
A Yes — and it is recommended: split concerns into separate states instead of one big object.