useEffect
You'll learn when an effect runs, and how the dependency array decides when it runs again.
useEffect in almost every app.Watch & read
Start with the required ones. The others are there when you need them.
See it step by step
Render first, then the effect. A changed dependency runs it again.
Explanation
A component's job is to return JSX. But sometimes you must also do something outside React, like change
the browser tab title, start a timer, or ask a server for data. That kind of work is called a side
effect, and useEffect is where it goes.
useEffect(() => {document.title = count + " new messages";}, [count]);
An effect runs after React has put the screen up. First the render, then the effect. The list at the
end, [count], is the dependency array. It tells React when to run the effect again:
[count]: after the first render, and again after any render wherecountchanged.[]: only once, after the first render.- no array at all: after every render.
An effect can return a function, called cleanup. React runs it before the effect runs again, and when the component leaves the screen. Use it to stop a timer you started.
In development, React runs each effect one extra time when the component first appears. It does this on purpose, to check your cleanup works. It does not happen in the real app.
People often set state in an effect with no dependency array. Setting state renders again, the effect runs again, sets state again, and the loop never ends. Always give the array.
When you read an effect, read the last line first: the dependency array tells you when it runs.
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 Profile() {2 const [count, setCount] = useState(0);3 const [name, setName] = useState("Rafi");45 useEffect(() => {6 console.log("effect ran");7 }, [count]);89 return (10 <div>11 <button onClick={() => setCount(count + 1)}>+1</button>12 <button onClick={() => setName("Nusrat")}>Rename</button>13 </div>14 );15}1617// The screen appears. You tap "+1" once, then "Rename" once.18// Count the runs in the real app (not the extra development check).
Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3When does an effect run, compared to the render?
- 2 / 3How often does
useEffect(() => { ... }, [])run in the real app? - 3 / 3What happens with
useEffect(() => { setCount(count + 1); }), with no array?
Explain it back
How confident are you with useEffect?
Done
useEffect and say when it runs, from its dependency array.