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.

GroupRendering & State
KindHook
SinceReact 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

initialStateInitial 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏