State with useState
You'll learn how useState remembers a value and redraws the screen when it changes.
Watch & read
Start with the required ones. The others are there when you need them.
See it step by step
Click, set state, render again.
Explanation
A component is a function that returns what the screen should show. React calls it to render. Normal variables are forgotten every time the function runs again, so they can't remember a click.
useState gives a component memory: const [count, setCount] = useState(0). count is the current
value, and setCount is how you change it. The 0 is only used the very first time.
Calling setCount(1) does not change count on the spot. It asks React to remember 1 and render the
component again. On that new render, count is 1, and the screen shows the new value. That loop
(event, set state, render, new screen) is how every interactive React app works.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1function Counter() {2 const [count, setCount] = useState(0);34 function handleClick() {5 setCount(count + 1);6 setCount(count + 1);7 }89 return <button onClick={handleClick}>{count}</button>;10}
setTasks(addTask(tasks, title)) adds a task. React only notices a change when it gets a new array. Fix addTask so it returns a new array and leaves the old one alone.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3In
useState(0), when is the0used? - 2 / 3What does calling the setter, like
setCount(5), do? - 3 / 3A component has
let likes = 0;and a button that runslikes = likes + 1. What happens on screen when you tap it?
Explain it back
How confident are you with State with useState?
Done
useState line and say what happens on screen when the setter is called.