Skip to content

Effects

The Course
•
20 min study

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

JavaScript
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.

When does the effect run? React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useState } from "react"; export default function App() { const [count, setCount] = useState(0); const [name, setName] = useState("Ada"); useEffect(() => { console.log("Effect ran. count is", count); }, [count]); return ( <main> <h1>Hello, {name}</h1> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Add 1</button>{" "} <button onClick={() => setName(name === "Ada" ? "Grace" : "Ada")}>Change name</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then 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 asThe effect runs
useEffect(fn, [count])after mounting, and after any render where count changed
useEffect(fn, [])only after mounting
useEffect(fn), with no listafter 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:

JavaScript
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:

JavaScript
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.

Exercise

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.

Find the missing dependency React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useState } from "react"; const SERVER = "study-server"; export default function App() { const [count, setCount] = useState(0); const [name, setName] = useState("Ada"); const label = `${name} has ${count}`; // Pretend to save the label to a server whenever it changes. useEffect(() => { console.log("Saved to", SERVER + ":", label); }, [count]); return ( <main> <h1>Hello, {name}</h1> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Add 1</button>{" "} <button onClick={() => setName(name === "Ada" ? "Grace" : "Ada")}>Change name</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then 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:

Text
Saved to study-server: Grace has 0
Saved to study-server: Grace has 1
Your working space React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useState } from "react"; const SERVER = "study-server"; export default function App() { const [count, setCount] = useState(0); const [name, setName] = useState("Ada"); const label = `${name} has ${count}`; // Pretend to save the label to a server whenever it changes. useEffect(() => { console.log("Saved to", SERVER + ":", label); }, [count]); return ( <main> <h1>Hello, {name}</h1> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Add 1</button>{" "} <button onClick={() => setName(name === "Ada" ? "Grace" : "Ada")}>Change name</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm 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
JavaScript
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.

Was this article helpful?

Your response is saved on this device.