Hooks 01 · Effects and refs
Effects (useEffect)
Syncing with the outside world, cleanup, race conditions and when you DON’T need an effect.
Loading lesson…
Hooks 01 · Effects and refs
Syncing with the outside world, cleanup, race conditions and when you DON’T need an effect.
Loading lesson…
So far you can do two things. Render: a component returns JSX from props and state. And react to the user: a handler like onClick changes state after a click. That covers a lot. But try writing an ordinary clock with just these two tools – one that shows the new time every second.
Nobody clicks on a clock, so there's no handler to put the code in. That leaves the component body. Let's try it – you know the timer setInterval from lesson JavaScript 07: it calls the given function again and again until you stop it.
function Clock() {// State with the current time. new Date() creates the date and time "now".// A function instead of a value = lazy initialisation (React basics 03): the date is created only on the first render.const [now, setNow] = useState(() => new Date())// ❌ A timer right in the component body:// every 1000 ms (= every second) put the new time into statesetInterval(() => setNow(new Date()), 1000)return <p>{now.toLocaleTimeString()}</p> // the time as text, say "14:05:09"}
It looks reasonable, but watch what happens:
Clock() for the first time. The component body starts timer no. 1.setNow. The state changed, so React calls Clock() again – that's how every render works (React basics 03).setInterval. Timer no. 2 is running. Nobody stopped the first one.So the clock is missing three things that neither the component body nor a handler can do:
useEffect gives you exactly these three things. By the end of section 1 the clock will work.
The component body tempts you to think "this code runs when the component appears". It doesn't work like that. The component body is a function and React calls it again on every render: after every state change, every time the parent re-renders, and in development mode (while you write and try the app on your own computer) even twice in a row – section 1 explains why. You don't control how many times or when.
So the component body takes only what can be repeated without harm: calculating from props and state what should be on the screen. You can run a calculation a hundred times – it gives the same result and leaves nothing behind. Starting a timer isn't like that: every call leaves something extra in the world.
A simple test helps. For every line, ask: would it matter if it ran ten times in a row?
| Line | Ten times in a row | Where it belongs |
|---|---|---|
const total = price * count | the same result every time, nothing left behind | ✅ in the component body |
const visible = items.filter(…) | the same list every time, nothing left behind | ✅ in the component body |
setInterval(…) | ten running timers | ❌ in an effect |
connect(roomId) | ten connections to the server | ❌ in an effect |
sendOrder(cart) | ten orders sent | ❌ in a handler (after a click) |
Read the table by rows: on the left a line of code, in the middle what would happen after ten calls, on the right where to write it. The functions connect and sendOrder are made up (connect to a chat, send an order).
It's the same as with the cook from the previous lessons: the cook can make a dish ten times and nothing happens, a failed one is simply thrown away. But if the cook called a supplier every time they cooked, ten deliveries would arrive. That's why while cooking, the cook only cooks – and everything that leaves something behind in the world comes afterwards, when the dish is on the table (the page is rendered). That "afterwards" is an effect.
You need an effect when both of these are true:
The table shows a few typical wishes. The middle column says what outside React the wish concerns, the right one whether it calls for an effect:
| I want… | What is "outside React" here | An effect? |
|---|---|---|
| the clock to show the new time every second | a browser timer | ✅ yes |
| the tab to show the number of unread messages | the tab title | ✅ yes |
| the chat to stay connected while it’s on the screen | a server | ✅ yes |
| the page to know how wide the window is | the browser window | ✅ yes |
| the user’s data to load once the profile is shown | a server | ✅ yes |
| the price to be calculated from the cart items | nothing – it’s just a calculation | ❌ no, calculate it in the component body |
| the order to be sent after a click | a server, but because of a click | ❌ no, it belongs in the handler |
We'll write the first five rows one by one in this lesson. The last two are the most common mistake – section 6 covers them.
What does such an effect look like? Imagine hiking through the country and setting up camp wherever you stop:
That's exactly how React runs effects: it sets up camp when the component appears; packs it up and sets it up again when whatever the effect depends on changes; and packs up for the last time when the component disappears. You only describe how to set up the camp, how to pack it up and where you're camping. React takes care of when to do which.
The broken clock from the introduction did the opposite: on every render it set up a new camp and never packed one up. Whoever doesn't pack up leaves burning campfires in the woods – and they pile up.
Almost every effect has the same shape. First you'll see it as a template with blanks – code about a camp – and right after that the same template filled in with the clock.
// useEffect is a function from React – you know import from lesson JavaScript 08import { useEffect } from 'react'// place = a prop: the spot where we campfunction MyComponent({ place }: { place: string }) {// useEffect(function, array) = "run this function only AFTER rendering"useEffect(() => {// ─── 1. SET UP CAMP (start) ─────────────────────────────// What do I switch on or set outside React after rendering?// (a timer, a connection to a server, an event listener = a function the// browser calls on, say, every key press – recipe in section 7)const camp = setUpCamp(place) // setUpCamp = a made-up function "set up a camp"// ─── 2. PACK UP CAMP (clean up) ─────────────────────────// What do I have to cancel before I leave?// You don't call this function – you just return it and React calls it itself.return () => {packUpCamp(camp) // packUpCamp = a made-up function "pack up the camp"}}, [place])// ─── 3. WHERE I'M CAMPING (dependencies) ──────────────────// An array with everything from the component the effect reads (here place).// When one of the values changes, React packs up the old camp and sets up a new one.return <div>…</div>}
The template has three parts and each comes with one question. Ask them before every effect:
Now let's fix the clock from the introduction. The answers to the three questions: I set up a timer, I pack it up with clearInterval (stopping a timer, from lesson JavaScript 07) and I'm not moving anywhere, because the effect reads nothing from the component.
import { useEffect, useState } from 'react'function Clock() {// State with the current time – the same as in the broken exampleconst [now, setNow] = useState(() => new Date())useEffect(() => {// 1. SET UP CAMP: start a timer that every second (1000 ms)// puts the new time into state → React re-renders the clockconst id = setInterval(() => setNow(new Date()), 1000)// setInterval returns a number (id) – we'll use it to stop the timer// 2. PACK UP CAMP: stop the timer with this id.// React calls this function when the clock disappears from the page.return () => clearInterval(id)}, [])// 3. WHERE I'M CAMPING: [] = an empty array. The effect reads nothing from the component, I'm not moving.// The camp is set up once (when the clock appears) and packed up when it disappears.// Rendering only "cooks": it returns JSX with the time as text, say "14:05:09"return <p>{now.toLocaleTimeString()}</p>}
Compare it with the broken clock from the introduction. The line with setInterval is the same, it just moved inside the effect. Thanks to that:
[], sees that nothing changed, and leaves the effect alone. One timer is running.| Part of the template | Question | In the clock |
|---|---|---|
| 1. The effect body | What do I set up here? | setInterval(…) |
| 2. The returned function (cleanup) | How do I pack it up? | clearInterval(id) |
| 3. The dependency array | Where am I camping? | I'm not moving: [] |
Read the table by rows: on the left a part of the template, in the middle the question it answers, on the right the answer in the clock. The cleanup is optional – an effect that starts nothing (say, it just rewrites some text) has nothing to pack up and returns nothing. You'll see that in section 2.
A timer, a connection to a server or an event listener keeps running on its own, even when the component disappears. That's like walking away and leaving the camp standing with the fire burning: do it all the time and a month later the woods are full of them. In an app this is called a memory leak: without the cleanup, after the clock was unmounted the timer would keep calling setNow on a component that no longer exists. And every new mount would add another timer.
The whole life of the clock's effect:
| What happens | What React does |
|---|---|
| The clock appears on the page | Runs the effect → the timer runs (the camp stands). |
| The clock re-renders every second | Nothing – the dependencies [] didn’t change, the camp stays. |
| The clock disappears from the page | Calls the cleanup → the timer stops (the camp is packed up). |
What you see: The clock from the example above. Below it is a log, into which the effect writes "▶ starting the interval" and the cleanup "■ cancelling the interval".
Try it:
The takeaway: Every "starting" has its own "cancelling". Thanks to that, two intervals never run at once, however many times the clock is mounted and unmounted.
Loading the interactive part…
The clock had an empty dependency array, so its effect ran only once. Now an effect that should run again every time the state changes. We want the browser tab's title to show the number of unread messages: "(3) React Course". But the title doesn't belong to React – it lives in document.title, outside JSX. So it's "the outside world" that we need to keep in sync with.
function Inbox() {const [unread, setUnread] = useState(0) // the number of unread messages// ❌ Not like this: writing to the outside world right while cooking// document.title = `(${unread}) React Course`// ✅ An effect: runs only after renderinguseEffect(() => {document.title = `(${unread}) React Course` // rewrites the tab title}, [unread]) // the effect reads unread → it runs again whenever unread changesreturn <button onClick={() => setUnread((u) => u + 1)}>A message arrived</button>}
What happens after a click:
setUnread orders a new render. React calls Inbox() – the cook makes new JSX. Nobody has touched the title yet.[unread]: has the value changed since last time? Yes (0 → 1), so it runs the effect and the title is rewritten.This effect starts nothing that keeps running – it just rewrites some text. So it doesn't strictly need a cleanup. The demo below has one anyway: when you leave the lesson, it restores the original title so it doesn't leave foreign text behind. Section 3 covers the dependency array in detail.
What you see: A counter of unread messages. The effect writes it into the title of this browser tab and restores the title in its cleanup.
Try it:
The takeaway: The state is in React, the title outside it. The effect keeps them in sync: after every change of unread it updates the title, and when leaving it cleans up after itself.
Loading the interactive part…
Dependencies are the answer to the third question: "where am I camping?" As long as you stay at the same spot, the camp stands. As soon as you move, you pack up the old camp and set up a new one.
How does React know you've moved? After every render it takes the dependency array and compares it item by item with the array from the previous render:
You've already seen both cases. The clock had [] – an empty array can't change, so the effect ran once. The tab title had [unread] – the effect ran after every change of the message count.
Now an example that also shows the cleanup on a change. The component should connect to the chat room the user picked. The function connect is made up: it connects to a room and returns a connection object that can disconnect().
// roomId = a prop: the name of the room the user picked (say "general")function ChatRoom({ roomId }: { roomId: string }) {useEffect(() => {const connection = connect(roomId) // 1. set up camp: connect to room roomIdreturn () => connection.disconnect() // 2. pack up camp: disconnect from it}, [roomId]) // 3. where I'm camping: in room roomIdreturn <h3>Welcome to #{roomId}</h3>}
The user switches from #general to #react:
roomId = "react".["general"], now ["react"] – a change.#general.#react.Without the cleanup the user would stay connected to both rooms and get messages from both. Without roomId in the array they would stay in the first room forever, even though the heading already shows another one.
The array can be written in three ways. The table says when the effect runs with each of them (fn is the effect function, a and b are values from the component):
| Syntax | When the effect runs |
|---|---|
useEffect(fn, [a, b]) | After the first render and every time a or b changes. The most common. |
useEffect(fn, []) | Only after the first render (and the cleanup when the component disappears). |
useEffect(fn) | No array: after every render. You rarely want that. |
You don't get to choose what goes in the array. It takes everything from the component that the effect reads: props, state and values calculated from them. It's not a list of "when I want the effect to run", but "what the effect works with".
Why does it matter? From lesson React basics 03 you know that every render has its own snapshot of values: in one render count is 0, in the next it's 1. The effect function is created inside a render, so it sees the values from the render it was created in. When the effect doesn't run again, it keeps working with the old snapshot. Here you can see it – a counter that should add one every second:
function Counter() {const [count, setCount] = useState(0)useEffect(() => {// every second set the counter to "count + 1"const id = setInterval(() => setCount(count + 1), 1000)return () => clearInterval(id)}, []) // ❌ the effect reads count, but it's not in the dependenciesreturn <p>{count}</p>}
What happens:
count is 0. The effect starts the timer. The function in the timer was created in this render, so for it count + 1 means 0 + 1.setCount(0 + 1). The counter shows 1 and the component re-renders.[] and [] – no change, it leaves the effect alone. So the timer is still running that original function with the snapshot count = 0.setCount(0 + 1) again. And so on. The counter freezes at 1.The effect "lied" about count – it claimed not to read it, so React never gave it a new snapshot. There are two possible fixes:
count to the dependencies. It works, but then the camp is torn down and set up again every second: the timer is cancelled and a new one created right away.count at all. That's better. The updater function from lesson React basics 03 does the job: instead of a new value you pass a function and React itself gives it the current value.// inside the Counter component above – it replaces its effectuseEffect(() => {// ✅ an updater: (c) => c + 1 means "take the current value and add 1" –// React supplies the current value, the effect doesn't have to read itconst id = setInterval(() => setCount((c) => c + 1), 1000)return () => clearInterval(id)}, []) // now the effect really reads nothing from the component, so [] is true
The same approach applies whenever a dependency bothers you: don't delete it from the array, change the code so the effect doesn't need it. The table shows the three most common cases – on the left what the effect reads, on the right how to get rid of it:
| The effect reads… | What to do |
|---|---|
| state only to calculate new state from it | an updater function: setCount((c) => c + 1) |
| a function written in the component body | move it inside the effect (the FAQ below explains) |
| a value it only wants to know when something happens, without starting over because of it | useEffectEvent – section 5 |
In the evening you order a pizza. A minute later you change your mind and order sushi. The sushi arrives in twenty minutes, the pizza in forty. If you're not careful, you eat the sushi, then the pizza arrives and you eat that too – even though you no longer wanted it. It's wiser to tell yourself: "I cancelled the pizza – if it turns up, I won't take it".
It's the same with loading data in an effect. The user clicks on Anna, then right away on Peter. Two requests are sent and the responses can arrive in any order. When Anna arrives after Peter, she overwrites him – and the screen shows a different person from the one selected.
// userId = a prop: the id of the user that was clickedfunction Profile({ userId }: { userId: number }) {// The loaded user. The type User | null means "a user, or nothing yet" (null = hasn't arrived yet).const [user, setUser] = useState<User | null>(null)useEffect(() => {let ignore = false // "I still want this order"// fetchUser = a made-up function: asks the server for a user and returns a Promise (JavaScript 07).// .then(…) = "when the response arrives, call this function with the data"fetchUser(userId).then((data) => {if (ignore) return // the order was cancelled → don't take the responsesetUser(data) // otherwise save the user into state → it shows up})// The cleanup: React calls it as soon as userId changes (or the profile disappears from the page)return () => {ignore = true // cancelling the order}}, [userId]) // the effect reads userId → it runs again on a changereturn <p>{user ? user.name : 'Loading…'}</p> // until the data arrives, show "Loading…"}
Let's go through a quick switch from Anna (id 1) to Peter (id 2):
| Time | What happens | ignore |
|---|---|---|
| 0 ms | The effect for Anna: sends request 1. | Anna: false |
| 100 ms | A click on Peter → the cleanup of Anna’s effect. | Anna: true |
| 100 ms | The effect for Peter: sends request 2. | Peter: false |
| 600 ms | Peter arrives → ignore is false → he’s shown. | Peter: false |
| 1200 ms | Anna arrives → ignore is true → she’s thrown away. | Anna: true |
Read the table from top to bottom as a timeline; the right column shows the value of ignore in the effect for Anna and in the effect for Peter. The important thing is that the ignore variable is created inside the effect, so every run of the effect has its own. The cleanup flips only its own, and that's how the old response recognises that nobody wants it any more. In camp terms: setting up camp = sending the request, packing up = saying "I don't want this response any more".
What you see: Buttons with names and a profile card that loads after a click. The fake API answers with a random delay of 0.3–1.5 s. The checkbox turns on the protection with ignore from the example above.
Try it:
The takeaway: Without the cleanup, whoever arrives last decides. With the cleanup, whoever was selected last decides – and that's what the user expects.
Loading the interactive part…
The example above waits for the response with .then(). But from lesson JavaScript 07 you know a more readable form: an async function in which await waits for the result. It's tempting to put async straight in front of the effect's function. That doesn't work:
// ❌ Not like this: async right on the effect's functionuseEffect(async () => {const data = await fetchUser(userId)setUser(data)}, [userId])
Why it doesn't work, step by step:
async function always returns a Promise (lesson JavaScript 07) – even when there's no return in it.ignore = true), you have nowhere to write it. Besides, a return inside an async function would run only after the await, and that's too late: React wants the cleanup right away.The fix: the effect's function stays ordinary (without async) and the asynchronous code goes inside it – into a nested async function you call right away. It's the same effect as in the Anna and Peter example, just with await instead of .then():
// inside the Profile component from the example above – it replaces its effectuseEffect(() => {let ignore = false // "I still want this order"// 1. SET UP CAMP: a nested async function – await is allowed in itasync function load() {const data = await fetchUser(userId) // wait for the server's responseif (ignore) return // userId changed in the meantime → throw the response awaysetUser(data) // otherwise store it in state → it shows}load() // call the function right away – otherwise nothing would happen// 2. PACK UP CAMP: the cleanup is returned at once, not after awaitreturn () => {ignore = true // "I don't want the pizza any more"}}, [userId]) // 3. WHERE I'M CAMPING: the effect reads userId
The effect's function runs instantly: it creates ignore, starts load() and returns the cleanup straight away. Meanwhile load waits for the server in the background – and when the response arrives, it checks ignore to see whether anyone still wants it. The name load is made up; the function can be called anything.
| Written as | What React gets | Does it work? |
|---|---|---|
useEffect(async () => { … }) | a Promise | ❌ the cleanup is never called, TypeScript reports an error |
useEffect(() => { fetchUser(…).then(…) }) | nothing, or a cleanup function | ✅ |
useEffect(() => { async function load() { … } load() }) | nothing, or a cleanup function | ✅ reads like ordinary code |
The table reads by rows: the way the effect is written on the left, what React gets from the effect's function in the middle, the result on the right. Between .then() and a nested async function pick whichever you like – they do the same. The whole recipe, including the "Loading…" state and an error, is in section 7.
In section 3 the rule was: what the effect reads goes in the dependencies, and when it changes, the effect starts over. Mostly that's what you want. But now and then you meet a value the effect needs to know, yet a change of it shouldn't make the effect start over.
You know this from the camp too. Every evening you cook dinner, and what you cook you decide in the evening, depending on what you feel like right then. If you change your mind about the food during the day, you won't pack up the camp and set it up again because of it. What you fancy for dinner isn't an answer to "where am I camping". It's something you look at only at the moment you need it.
Let's take the counter from section 3 and give it a step prop. Every 2 seconds it should add whatever the step is right now. The user changes the step with a button whenever they like.
By the rule from section 3 – the effect reads step, so we write it in the array:
function Counter({ step }: { step: number }) {const [count, setCount] = useState(0)useEffect(() => {// every 2 seconds (2000 ms) add step to the counterconst id = setInterval(() => setCount((c) => c + step), 2000)return () => clearInterval(id)}, [step]) // the effect reads step → it's in the dependenciesreturn <p>{count}</p>}
The counter adds the right step. But every change of the step is a change of a dependency, which means packing up the camp and setting up a new one: the timer is cancelled and started again, so the wait for the next tick starts from zero. If you change the step more often than once every 2 seconds, the counter won't move at all.
What if we simply deleted step from the array and left it empty? The timer would run undisturbed, but that's exactly the lie from section 3: the function in the timer stays with the snapshot from the first render and keeps adding the first step forever, however the user changes it. And an updater function won't help this time – it supplies the current count, but not step.
We need both: a timer that runs undisturbed, and the current step on every tick. That's what useEffectEvent is for (in React since version 19.2). You take the code that should run "when it happens" out of the effect into a separate function:
// useEffectEvent is imported from React just like useEffectimport { useEffect, useEffectEvent, useState } from 'react'function Counter({ step }: { step: number }) {const [count, setCount] = useState(0)// "What to do when the timer ticks."// On every call, a function from useEffectEvent sees the CURRENT props and state –// so the latest step too.const onTick = useEffectEvent(() => {setCount((c) => c + step)})useEffect(() => {const id = setInterval(() => onTick(), 2000) // 1. set up camp: call onTick every 2 sreturn () => clearInterval(id) // 2. pack up camp: cancel the timer}, [])// 3. where I'm camping: the effect itself reads nothing from the component → [].// onTick doesn't belong in the dependencies – that's exactly what useEffectEvent is for.return <p>{count}</p>}
That splits the code into two parts, each with its own job:
| Part | Takes care of… | When step changes |
|---|---|---|
the effect (useEffect) | when the timer runs: starting and cancelling it | doesn’t react – the timer keeps running |
the effect event (useEffectEvent) | what happens on a tick | uses the new step on the next tick |
Read the table by rows: on the left a part of the code, in the middle what it's in charge of, on the right what it does when the user changes the step. You can try all three versions:
What you see: A counter that adds the step every 2 seconds. At the top you switch between the three versions from the lesson (A, B, C), below them you change the step. The log at the bottom shows when the timer started (▶) and when it was cancelled (■).
Try it:
The takeaway: What's in the dependencies restarts the effect. What a function from useEffectEvent reads doesn't – the function looks at the current value only at the moment someone calls it.
Loading the interactive part…
One question decides: should a change of this value tear the camp down and set it up again?
| Value | Tear down and set up again? | Where it goes |
|---|---|---|
| roomId in the chat from section 3 | yes – a different room is a different connection | in the dependencies |
| userId when loading a profile (section 4) | yes – a different user means different data | in the dependencies |
| step in the counter | no – the timer should keep running | useEffectEvent |
| the chat setting "play a sound on a new message" | no – the connection stays, you just check the setting at the next message | useEffectEvent |
The last row is the same case as the counter's step, only in a chat: the effect holds the connection (it depends on roomId) and a function from useEffectEvent finds out at every incoming message whether it should play a sound right now.
Effects are doors out of React. The most common mistake is to use them even where there's no "outside" – as if you went from the living room to the kitchen via the balcony. It works, but it's slower, and sooner or later you'll fall. Before you write useEffect, ask yourself: which system outside React am I syncing with here? If you have no answer, you probably don't need an effect.
// ❌ An effect chases state that can be calculatedconst [items, setItems] = useState<Item[]>([]) // the cart itemsconst [total, setTotal] = useState(0) // the total price as another piece of stateuseEffect(() => {// reduce (JavaScript 05) adds up the prices of all the itemssetTotal(items.reduce((sum, i) => sum + i.price, 0))}, [items]) // after every change of the items, recalculate and save// ✅ Calculate it during render – an ordinary variable, no state and no effectconst total = items.reduce((sum, i) => sum + i.price, 0)
The effect version renders the component twice: first with the new items and the old total, and only then does the effect call setTotal and cause a second render with the right number. For a split second the screen shows a wrong total. And above all there's no outside system here – just a calculation. It passes the test from the introduction too: calculating the total ten times in a row harms nothing, so it belongs in the component body.
// sendOrder and showToast are made-up functions: send the order, show a short message// ❌ A click only sets a "submitted" flag and an effect "reacts" to itconst [submitted, setSubmitted] = useState(false)useEffect(() => {if (submitted) {sendOrder(cart)showToast('Ordered!')}}, [submitted])// ✅ Do it right where the event happened – in the button's handlerfunction handleOrder() {sendOrder(cart)showToast('Ordered!')}// in the component's JSX: <button onClick={handleOrder}>Order</button>
The order should be sent because the user clicked – not because the component rendered. The code belongs in the handler. The effect version is indirect and can run when you don't expect it (say, when the component is mounted again).
The table sums up both examples and adds four more situations. On the left is what you want to do, in the middle the tempting solution with an effect, and on the right what to write instead:
| Situation | ❌ An effect | ✅ A better solution |
|---|---|---|
| A value calculated from props/state | useEffect → setTotal(…) | Calculate it during render (useMemo from Advanced React 04 if needed) |
| Reacting to a click / submit | Set a flag and react in an effect | Do it right in the handler |
| Resetting state when a prop changes | useEffect(() => setX(init), [id]) | <Form key={id} /> |
| Telling the parent about a change | useEffect(() => onChange(x), [x]) | Call onChange in the same handler as setX |
| Chaining state | An effect sets state that triggers another effect… | Calculate everything in one handler |
| Loading data | A bare fetch in an effect | TanStack Query / a router loader / use() (lessons Advanced React 07 and 08) |
On the rows that had no example of their own in the lesson:
key. React then throws the old component away and creates a new one – the "key as a reset" trick from lesson React basics 02.onChange prop, call it in the same handler in which you change your own state. An effect would do it one render later.This section brings nothing new – it puts the whole lesson into steps you can come back to when you write your own code. You'll find the same pattern in the Cheat sheets on the React tab.
Write an effect only when both are true: something should happen because the component is on the screen (not because of a click), and it concerns something outside React (a timer, the browser window and tab, a server). Otherwise don't write one – a calculation belongs in the component body, a reaction to a click in a handler (section 6).
Put the answers into the template from section 1. The functions setUpCamp and packUpCamp are made up – replace them with what your effect really does:
// inside a component, at the top next to useState – never in a condition or a click handler// place = a prop or state the effect works with (a room, a user id…)useEffect(() => {// ─── 1. SET UP CAMP (start) ─────────────────────────────// Start what should run – and keep whatever you'll need for the cleanup.const camp = setUpCamp(place) // say setInterval(…) or connect(…)// ─── 2. PACK UP CAMP (clean up) ─────────────────────────// Return a function that does the exact opposite of step 1. React calls it.return () => {packUpCamp(camp) // say clearInterval(…) or disconnect()}}, [place])// ─── 3. WHERE I'M CAMPING (dependencies) ──────────────────// Everything from the component the effect reads. It reads nothing? Write [].
The most common pairs in one place. Each row is one thing an effect starts: on the left how you start it, in the middle column what stops it in the cleanup, and on the right where the lesson has an example.
| 1. I set up (effect) | 2. I pack up (cleanup) | Example |
|---|---|---|
const id = setInterval(fn, 1000) | clearInterval(id) | section 1 – the clock |
const t = setTimeout(fn, 400) | clearTimeout(t) | section 4 – debounce |
const c = connect(roomId) | c.disconnect() | section 3 – the chat |
let ignore = false | ignore = true | section 4 – loading data |
const ctrl = new AbortController() | ctrl.abort() | section 4 – cancelling a request |
window.addEventListener('resize', fn) | window.removeEventListener('resize', fn) | the recipe below |
document.title = … | nothing, or restore the original title | section 2 – the title |
The only pair from the table the lesson hasn't shown yet. You know listeners with addEventListener from lesson JavaScript 02 – the browser calls the given function every time the event happens. The resize event happens on every change of the window size. The opposite is removeEventListener, which removes the listener:
function WindowWidth() {// window.innerWidth = the window width in pixels; a function = lazy initialisation (React basics 03)const [width, setWidth] = useState(() => window.innerWidth)useEffect(() => {// The function the browser calls on every change of the window sizefunction handleResize() {setWidth(window.innerWidth) // save the new width → it re-renders}window.addEventListener('resize', handleResize) // 1. set up camp: start listeningreturn () => window.removeEventListener('resize', handleResize) // 2. pack up camp: stop listening}, []) // 3. where I'm camping: the effect reads nothing from the component (setWidth never changes) → [] is enoughreturn <p>The window is {width} px wide.</p>}
Why does handleResize have its own name? removeEventListener removes a listener only when it gets the same function you passed to addEventListener. If you passed each of them a new arrow () => …, they would be two different functions (even though they look the same – lessonJavaScript 09 explains why) and the listener would stay attached.
The most common effect of all. It combines section 4 (ignore and a nested async function) with errors through try/catch from lesson JavaScript 07. The "Loading…" state isn't stored anywhere – it's worked out from there being neither data nor an error yet:
// The shape of the data that comes from the serverinterface User { id: number; name: string }// fetchUser = a made-up function: asks the server for a user and returns a Promisefunction Profile({ userId }: { userId: number }) {const [user, setUser] = useState<User | null>(null) // the loaded data (null = nothing yet)const [error, setError] = useState<string | null>(null) // the error text (null = no error)useEffect(() => {let ignore = false // "I still want this response"// 1. SET UP CAMP: start loadingasync function load() {try {const data = await fetchUser(userId) // wait for the serverif (!ignore) setUser(data) // store it only if I still want the response} catch (err) { // err = what went wrong (here it's enough to know something did)if (!ignore) setError('The user could not be loaded')}}load()// 2. PACK UP CAMP: a response arriving after the cleanup is thrown awayreturn () => {ignore = true}}, [userId]) // 3. WHERE I'M CAMPING: a different userId = a new load// Rendering only "cooks" from state – no loading hereif (error !== null) return <p className="bad">{error}</p>if (user === null) return <p>Loading…</p> // neither data nor an error → still loadingreturn <p>{user.name}</p>}
In bigger apps data is usually loaded by a library that also remembers results and retries by itself after an error – that's lesson Advanced React 08. Inside, though, it does exactly this.
useEffectEvent), don't delete it.useEffect isn't async – the asynchronous code is inside it (section 4).ignore or AbortController).Two places in a finished effect template: what to set up and where you're camping. You'll see the result on the browser tab.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
Two easy challenges practise one thing each: an event listener with a cleanup (the recipe from section 7) and useEffectEvent (section 5). The stopwatch combines sections 1 to 3 (a timer, cleanup, an updater and the tab title). The search adds section 4: you have to make sure the search starts only once typing stops and only the results of the last query are shown. All challenges have their effects laid out by the template from the lesson. For every effect, first tell yourself: what do I set up here, how do I pack it up and where am I camping – the template is in sections 1 and 7.
A listener on the whole window that runs only while the panel is open. What exactly should happen is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
A timer that saves the current text every second but doesn't restart because of typing – exactly the situation useEffectEvent is for. What exactly should happen is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
Two effects, each taking care of one thing outside React: the first of the timer, the second of the tab title. In each you fill in what to set up and how to pack it up. What exactly the stopwatch should do is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
A real scenario from every app: an autocomplete that doesn't flood the server with a query after every letter, doesn't show stale results and doesn't search for an empty field. What exactly should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
ignore or AbortController throws away the old order.