Sub topic 6
Remembering values with useState
This chapter assumes you can write a React function component and pass it props, and that you know JavaScript array destructuring. Props are inputs a parent gives a component. State is data the component keeps for itself between renders.
Why a plain variable is not enough
A component is a function that React calls every time it needs to redraw. Local variables are created fresh on each call, so they lose their value. Changing a local variable also does not tell React to redraw anything.
useState solves both problems. It stores a value for the component outside the function call. It also gives you a function that updates the value and asks React to render again.
The useState hook
import { useState } from 'react'
function Counter({ label }) {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
)
}
export default CounteruseState(0) returns an array with two items. The first is the current value, which is 0 on the first render. The second is the setter. Calling setCount(1) stores the new value and schedules a re-render. During that render, useState returns the stored value instead of 0.
Rules for hooks
- Call hooks only at the top level of a component. Do not call them inside loops, conditions, or nested functions.
- Call hooks only from components or from your own custom hooks.
React matches each useState call to its stored value by call order, so the order must be the same on every render.
Updating from the previous value
A state update does not change the variable in the current render. The count in that render stays the same. This matters when you update twice in a row.
function addTwoWrong() {
setCount(count + 1)
setCount(count + 1) // still uses the old count, so the total rises by 1
}
function addTwo() {
setCount((c) => c + 1)
setCount((c) => c + 1) // each call receives the latest value, so the total rises by 2
}Pass an updater function whenever the new value depends on the old one.
Objects and arrays
React detects a change by comparing the old and new values. If you mutate an object or array and pass the same reference, React sees no change and skips the re-render. Create a new value instead.
const [items, setItems] = useState([])
function addItem(text) {
setItems([...items, text]) // new array, so React re-renders
}Do not use items.push(text) followed by setItems(items). That passes the same array back.
Common errors
| Symptom | Likely cause |
|---|---|
| Screen does not update | State was mutated instead of replaced |
| Value is one step behind after `setX` | You logged the variable in the same render, which still holds the old value |
| "Rendered more hooks than during the previous render" | A hook sits inside a condition or loop |
Exercise
A button handler runs setCount(count + 1) three times in a row, with count starting at 0. What is count after the next render, and how do you make it 3?
Show answer
It becomes 1, because all three calls read the same count from the current render. Use the updater form, setCount((c) => c + 1), three times, so each call receives the latest value.