Today: effects
Everything so far has happened in two places: during render, where a component works out its JSX, and in event handlers, which respond to clicks and typing. Some code fits neither. Starting a timer, loading data from a server, or connecting to a chat should happen because a component is on the screen, not because someone clicked. That's what effects are for.
useEffect
useEffect(() => {
console.log("Effect ran. count is", count);
}, [count]);useEffect takes a function, and the rule is short: React runs it after it
has rendered and updated the page. The array at the end says when to run it
again.
That array is the dependency list. React runs the effect after the first render, and then again only after a render where something in the list has changed.
Run the lab and watch the console. Then click Add 1 twice and Change name twice.
npm install and npm run dev. Check what you saw
Effect ran. count is 0 appears once at the start, then once for each
Add 1. Change name re-renders the page but doesn't run the effect,
because name isn't in the dependency list.
Three kinds of dependency list
The first time a component appears on the screen is called mounting. Try each list below in the lab: predict what the console shows when you click Add 1 and Change name, then check.
| Written as | The effect runs |
|---|---|
useEffect(fn, [count]) | after mounting, and after any render where count changed |
useEffect(fn, []) | only after mounting |
useEffect(fn), with no list | after every render |
Check your prediction
With [], the console shows Effect ran. count is 0 once and then nothing,
however often you click: an empty list never changes. With no list, every click
of either button logs a line, because every click causes a render. After two
Add 1 and two Change name, that's four more lines, and the two after
Change name both show count is 2.
The dependency list isn't a choice about when you'd like the effect to run. It
should name every value from the component that the effect reads: props, state,
and variables calculated from them. Here the effect logs count, so count
must be in the list. If it read name too, name would belong there as well.
A value declared outside the component never changes between renders, so it
doesn't go in the list.
Going further: exactly when effects run
"After the page updates" is close enough for now. More precisely, React runs an effect after it has put the render's changes into the page. Usually the browser draws the screen first, but an effect caused by a click may run just before. The effect still runs on the same thread as everything else, so a long loop in an effect freezes the page like a long loop anywhere.
To decide whether a dependency changed, React compares old and new with
Object.is, which works like ===. On your own computer, the React Hooks
lint rule (installed by many project templates) warns about missing
dependencies. Fix the list rather than silencing it.
StrictMode runs effects twice
A new project from npm create vite wraps App in <StrictMode> in
main.jsx. In development, StrictMode runs each effect, cleans it up, and runs
it again on mounting, to show you effects that don't clean up after themselves.
You may see the initial setup log twice; it doesn't mean every later update
runs twice. The labs don't use StrictMode, so you see one setup on mounting.
Don't use an effect for what render can do
Suppose a form has two inputs, first name and last name, and you want to show the full name underneath. The full name is just the other two joined together. A common mistake is to keep it in its own state and update it with an effect:
const [first, setFirst] = useState("Ada");
const [last, setLast] = useState("Lovelace");
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(first + " " + last);
}, [first, last]);It works, but it's wasteful and fragile. When you type a letter, React renders
once with the new first and the old fullName, runs the effect, which
sets fullName, and then renders a second time. For that first render the
screen is out of step: the input says one thing and the full name says another.
fullName doesn't need to be state at all, because React can work it out from
first and last every time it renders:
const [first, setFirst] = useState("Ada");
const [last, setLast] = useState("Lovelace");
const fullName = first + " " + last;One render, and it can't be out of step: whenever first or last changes, the
next render recomputes fullName. A good rule: if a value can be calculated
from props or state you already have, calculate it while rendering. Use an
effect to keep something outside React in step: a timer, a network request,
the page title.
The save that doesn't happen
This lab pretends to save a label such as Ada has 0 to a server whenever the label changes. Click Add 1: a save appears in the console. Now click Change name: the heading says Grace, but nothing is saved, so the "server" still thinks the name is Ada.
npm install and npm run dev. Fix the dependency list so that every change to the label is saved, and no other renders cause a save. After the fix, Change name then Add 1 should log:
Saved to study-server: Grace has 0
Saved to study-server: Grace has 1npm install and npm run dev. Hint 1: the idea
List the values the effect reads, one by one, and ask of each: is it declared in the component, so it can be different on the next render? Those, and only those, belong in the dependency list.
Hint 2: a first step
The effect reads two names: SERVER and label. SERVER is declared above
the component, so it's the same on every render. label is worked out inside
the component, from name and count, on every render. Which of the two is
missing from the list, and does count still need to be there?
Show one solution
useEffect(() => {
console.log("Saved to", SERVER + ":", label);
}, [label]);The effect reads label, so label is the dependency. It changes whenever
name or count does, which is exactly when a save is needed. SERVER is
outside the component and never changes, so it stays out of the list.
[name, count] would also work here, but listing what the effect reads is the
rule that keeps working when the code changes.
Completion is saved in this browser only. It does not measure mastery.