React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
Watch useEffect on a timeline with real render counts: the dependency array deciding re-runs, a timer cleanup that keeps one timer alive, the leak StrictMode exposes, and two effects you should delete (a copied total and a click flag).
What you will learn
- Place an effect on the timeline: render, page update, then effect
- Predict re-runs from the dependency array: none, empty or with values
- Write a cleanup that stops what the effect started, and see why StrictMode runs it twice
- Replace effects that copy values or react to clicks with render-time code or event handlers
Before you start
- React state with useState
- JavaScript timers: setInterval and clearInterval
An effect is for one job: keeping something outside React in sync with your component. The browser tab title, a timer, a request to a server, a listener on the window. React can't draw those for you, so you reach out to them after the page is ready.
This article puts effects on a timeline and counts every render, using the lecture's small demos. The second half is just as useful: two effects you should delete.
Render, page, then the effect
import { useEffect, useState } from 'react'
export default function TaskTitle() {
const [done, setDone] = useState(0)
const [dark, setDark] = useState(false)
console.log('render:', { done, dark })
useEffect(() => {
// runs AFTER React has updated the page
document.title = `${done} tasks done`
console.log('effect: title =', document.title)
}, [done]) // again only when done changes
const add = () => setDone(done + 1)
const flip = () => setDark(!dark)
return (
<div className={dark ? 'card dark' : 'card'}>
<button onClick={add}>Done: {done}</button>
<button onClick={flip}>Dark</button>
</div>
)
}
On the first render the logs come out in exactly that order:
render: { done: 0, dark: false }
page: Done: 0
effect: title = 0 tasks done
The dependency array decides re-runs
Line 12, [done], is the dependency array. After the effect runs, React remembers it. After every later render, React compares the new array with the old one. Different values: the effect runs again. Same values: it is skipped. Click Done, then Dark:
render: { done: 0, dark: false }
effect: title = 0 tasks done
click: Done
render: { done: 1, dark: false }
effect: title = 1 tasks done
click: Dark
render: { done: 1, dark: true }
effect ran 2 times in 3 renders
Clicking Done changes done from 0 to 1, so [1] differs from [0] and the title updates. Clicking Dark renders a third time, but done is still 1, so the effect is skipped. Two effect runs in three renders.
Three ways to write the array
const runs = { none: 0, empty: 0, done: 0 }
function Probe() {
const [done, setDone] = useState(0)
const [dark, setDark] = useState(false)
useEffect(() => { runs.none++ })
useEffect(() => { runs.empty++ }, [])
useEffect(() => { runs.done++ }, [done])
const add = () => setDone(done + 1)
const flip = () => setDark(!dark)
return <>
<button onClick={add}>Done</button>
<button onClick={flip}>Dark</button>
</>
}
await show(<Probe />) // render 1
await click('Done', false) // render 2: done changes
await click('Dark', false) // render 3: dark only
console.log('no array:', runs.none, 'times')
console.log('[]: ', runs.empty, 'time')
console.log('[done]: ', runs.done, 'times')
no array: 3 times
[]: 1 time
[done]: 2 times
| Array | Runs | Here |
|---|---|---|
| none | after every render | 3 times |
[] | once, after the first render | 1 time |
[done] | first render, then whenever done changes | 2 times |
Cleanup: stop what the effect started
import { useEffect, useState } from 'react'
export default function Ticker() {
const [ticks, setTicks] = useState(0)
const [delay, setDelay] = useState(1000)
useEffect(() => {
console.log('effect: start', delay, 'ms timer')
const tick = () => setTicks((t) => t + 1)
const id = setInterval(tick, delay)
return () => {
// still the delay this effect started with
console.log('cleanup: stop', delay, 'ms timer')
clearInterval(id)
}
}, [delay])
const faster = () => setDelay(500)
return (
<div className="card">
<p>Ticks: {ticks}</p>
<button onClick={faster}>Faster</button>
</div>
)
}
After the first render, the effect starts a browser timer with setInterval. Every second it calls setTicks((t) => t + 1), which always adds one to the latest value. Line 10 returns a function: the cleanup.
Click Faster and delay becomes 500. The array changed, so the effect must run again. But first React runs the old effect's cleanup, and that old cleanup still sees delay as 1000, the value from its own render:
effect: start 1000 ms timer
after 2 s: Ticks: 2, timers running: 1
click: Faster
cleanup: stop 1000 ms timer
effect: start 500 ms timer
after 1 s: Ticks: 4, timers running: 1
One timer stopped, one started, and never two at once. The cleanup also runs when the component goes away (unmounts):
effect: start 1000 ms timer
click: Faster
cleanup: stop 1000 ms timer
effect: start 500 ms timer
unmount
cleanup: stop 500 ms timer
timers running: 0
Every effect run has its cleanup: start 1000, stop 1000, start 500, stop 500. Nothing is left behind.
StrictMode runs it twice, on purpose
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App'
// development only: React runs every effect,
// its cleanup, then the effect again
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
A Vite React app wraps App in StrictMode. It is on only in development (npm run dev), not in the build you publish. When a component appears, StrictMode runs the effect, then its cleanup, then the effect again, as a fake unmount and mount that tests your cleanup:
effect: start 1000 ms timer
cleanup: stop 1000 ms timer
effect: start 1000 ms timer
after 2 s: Ticks: 2, timers running: 1
Because the cleanup is right, the second run is harmless: Ticks: 2 after two seconds, one timer.
No cleanup: two timers
function LeakyTicker() {
const [ticks, setTicks] = useState(0)
useEffect(() => {
console.log('effect: start a timer, no cleanup')
setInterval(() => setTicks((t) => t + 1), 1000)
}, [])
return <p>Ticks: {ticks}</p>
}
effect: start a timer, no cleanup
effect: start a timer, no cleanup
after 2 s: Ticks: 4
timers running: 2
StrictMode started the effect twice and nothing stopped the first timer, so the clock runs at double speed. StrictMode doesn't cause this bug, it shows it. Every effect that starts something needs a cleanup.
Do you need an effect at all?
A value copied by an effect
import { useEffect, useState } from 'react'
type Props = { price: number }
// the same cart, with the total copied by an effect
export default function Cart({ price }: Props) {
const [qty, setQty] = useState(1)
const [total, setTotal] = useState(0)
console.log('render:', { qty, total })
useEffect(() => {
setTotal(price * qty) // one more render, to copy
}, [price, qty])
const add = () => setQty(qty + 1)
return (
<div className="card">
<p>Qty: {qty} Total: {total}</p>
<button onClick={add}>+1</button>
</div>
)
}
render: { qty: 1, total: 0 }
render: { qty: 1, total: 15 }
click: +1
render: { qty: 2, total: 15 }
render: { qty: 2, total: 30 }
renders: 4
Render 1 shows Total: 0, which is wrong. The effect sets the total, which costs another render. Click +1 and render 3 still shows 15, wrong again, until the effect fixes it in render 4. Two renders for every change, to copy a value React already knew. Work it out during the render instead:
import { useState } from 'react'
type Props = { price: number }
export default function Cart({ price }: Props) {
const [qty, setQty] = useState(1)
const total = price * qty // worked out in render
console.log('render:', { qty, total })
const add = () => setQty(qty + 1)
return (
<div className="card">
<p>Qty: {qty} Total: {total}</p>
<button onClick={add}>+1</button>
</div>
)
}
render: { qty: 1, total: 15 }
click: +1
render: { qty: 2, total: 30 }
renders: 2
Right the first time, and two renders instead of four for the same two steps.
A click handled by an effect
import { useEffect, useState } from 'react'
// the same button, the click handled by an effect
export default function Save() {
const [saved, setSaved] = useState(false)
const [message, setMessage] = useState('')
console.log('render:', { saved, message })
useEffect(() => {
if (saved) setMessage('Task saved')
}, [saved])
const save = () => setSaved(true)
return (
<div className="card">
<button onClick={save}>Save</button>
<p>{message}</p>
</div>
)
}
render: { saved: false, message: '' }
click: Save
render: { saved: true, message: '' }
render: { saved: true, message: 'Task saved' }
page: Task saved
renders: 3
The click only sets a flag. The message appears one render late, after the effect notices the flag. When a click is the reason, the handler is the place:
import { useState } from 'react'
export default function Save() {
const [message, setMessage] = useState('')
console.log('render:', { message })
function save() {
// the click is the reason, so the work goes here
setMessage('Task saved')
}
return (
<div className="card">
<button onClick={save}>Save</button>
<p>{message}</p>
</div>
)
}
render: { message: '' }
click: Save
render: { message: 'Task saved' }
page: Task saved
renders: 2
Recap
| Idea | What to remember |
|---|---|
| Timing | Render, page update, then the effect |
| Dependency array | Compared after every render; same values mean the effect is skipped |
| Cleanup | Runs before the next effect and on unmount; it sees its own render's values |
| StrictMode | Development only: effect, cleanup, effect; a good cleanup makes it harmless |
| Derived values | Compute in render, no state, no effect |
| Clicks | Do the work in the event handler |
Try it yourself: add a "Slower" button to the Ticker that sets the delay to 2000, and predict the cleanup and effect lines before you click it. Next: lifting state up, refs and React DevTools.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
React State, Events, Lists and Conditional Rendering: Follow One Click
Follow one click through a React counter, render by render: what useState hands back, why a plain variable never updates the page, ternaries and &&, map with keys, and the index-as-key bug that moves a typed note to the wrong task.
Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
A task board where the filter is stuck in one component, fixed by lifting it to App. Then useRef as a box React does not watch (three clicks, zero renders), a ref that refocuses an input, and the tree React DevTools shows.
Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
Four versions of an add-task form, traced with real logs: a controlled input, a classic onSubmit, a form action that gets FormData and resets itself, and useActionState with a pending button from useFormStatus, plus the draft trick that keeps typed text after an error.
React Context and Custom Hooks: Share One Value, Reuse the Logic
Replace three hops of prop drilling with a context, see the nearest Provider win, count which components re-render on a theme toggle, then pull localStorage logic into a useLocalStorage hook and break the rules of hooks on purpose.
