State and events · Lesson 7 of 21
useState: a component's memory
Why a plain variable doesn't work, re-rendering, and updater functions.
Try a counter with a plain variable and the number on the page never changes. Why? 1) A local variable resets every time the function runs, and 2) changing it doesn't tell React to redraw.
useState fixes both: it gives you a value React remembers between renders, and a set function that makes React re-render the component with the new value.
function App() {
let plain = 0
const [count, setCount] = useState(0)
return (
<div>
<p>plain: {plain} · state: {count}</p>
<button onClick={() => { plain++; console.log("plain is", plain) }}>plain++</button>
<button onClick={() => setCount(count + 1)}>state + 1</button>
</div>
)
}- ▶const [count, setCount] = useState(0)
- 2// click: setCount(count + 1)
- 3// React re-runs App()
- 4const [count, setCount] = useState(0)
- 5return <p>{count}</p>
Variables
| count | 0 |
| render | 1 |
Output
First render: count = 0.
useState's 0 is used only the first time. After that React returns the value it remembers.
Updater functions
Within one render, count is fixed, like a snapshot. Call setCount(count + 1) three times in a row and all three see the same count: the result is +1. When the new value depends on the old one, pass a function: setCount(c => c + 1).
function App() {
const [a, setA] = useState(0)
const [b, setB] = useState(0)
function plusThreeWrong() {
setA(a + 1)
setA(a + 1)
setA(a + 1)
}
function plusThreeRight() {
setB((n) => n + 1)
setB((n) => n + 1)
setB((n) => n + 1)
}
return (
<div>
<p>a = {a} <button onClick={plusThreeWrong}>+3 (wrong)</button></p>
<p>b = {b} <button onClick={plusThreeRight}>+3 (right)</button></p>
</div>
)
}What's the output?
function App() {
const [n, setN] = useState(5)
useEffect(() => {
setN(n + 1)
setN(n + 1)
}, [])
return <p>{n}</p>
}What will the page show?
Exercise
Build an XP counter: a +10 button adds 10, a Reset button sets it to zero, and the text reads XP: N. The checker presses +10 three times.
XP: 30 +10 Reset
function App() {
return (
<div>
<p>XP: 0</p>
<button>+10</button>
<button>Reset</button>
</div>
)
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.