- Home
- /
- Tutorials
- /
- React Tutorial
- /
- useState Explained
State and Reducers
useState Explained
A component function runs again on every render, so a plain variable resets every time. State is the box React keeps for you between those runs.
Why a normal variable fails
The component function re-runs from the top on each render. Any let inside it is created fresh, so an update made during one render is gone by the next - and nothing tells React to re-render in the first place.
Plain variable versus state
jsx
function BrokenCounter() {
let count = 0 // recreated on every render
return (
<button onClick={() => { count = count + 1 }}>
Plain variable: {count} (never changes)
</button>
)
}
function WorkingCounter() {
const [count, setCount] = React.useState(0)
return (
<button onClick={() => setCount(count + 1)}>
State: {count}
</button>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
<div style={{ display: "grid", gap: 8, justifyItems: "start" }}>
<BrokenCounter />
<WorkingCounter />
</div>
)