React useEffect
Rendering should be pure: compute JSX from props and state, nothing more. But apps also need side effects — starting a timer, subscribing to events, updating the document title, connecting to a server. useEffect lets you run such code after React has updated the screen, and clean it up later.
useEffect(() => {
// setup: runs after render
return () => {
// cleanup (optional): runs before the next effect and on unmount
};
}, [dependencies]);When does an effect run?
The second argument, the dependency array, controls it:
| Dependencies | Effect runs |
|---|---|
| (omitted) | after every render |
[] |
once, after the first render (mount) |
[a, b] |
after the first render and whenever a or b changed |
import { useState, useEffect } from 'react';
export default function App() {
const [count, setCount] = useState(0);
const [name, setName] = useState('');
useEffect(() => {
console.log('every render');
});
useEffect(() => {
console.log('mounted (runs once)');
}, []);
useEffect(() => {
console.log(`count changed to ${count}`);
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<button onClick={() => setCount(count + 1)}>Count: {count}</button>{' '}
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="Typing doesn't change count" />
</div>
);
}Watch the console: typing in the input logs only "every render", while clicking the button also logs the count effect.
Cleanup
Effects that start something must stop it. Return a cleanup function; React calls it before re-running the effect and when the component unmounts. Without it, timers and listeners leak and keep running:
import { useState, useEffect } from 'react';
function Clock({ timezone }) {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
console.log(`start timer for ${timezone}`);
const id = setInterval(() => setNow(new Date()), 1000);
return () => {
console.log(`stop timer for ${timezone}`);
clearInterval(id);
};
}, [timezone]);
return (
<p style={{ fontSize: 24, fontFamily: 'monospace' }}>
{now.toLocaleTimeString('en-GB', { timeZone: timezone })} ({timezone})
</p>
);
}
export default function App() {
const [show, setShow] = useState(true);
const [tz, setTz] = useState('Asia/Ho_Chi_Minh');
return (
<div>
<button onClick={() => setShow(!show)}>{show ? 'Hide' : 'Show'} clock</button>{' '}
<select value={tz} onChange={(e) => setTz(e.target.value)}>
<option>Asia/Ho_Chi_Minh</option>
<option>Europe/London</option>
<option>America/New_York</option>
</select>
{show && <Clock timezone={tz} />}
</div>
);
}Changing the time zone logs stop for the old value and start for the new one. Hiding the clock logs only stop.
Subscribing to browser events
import { useState, useEffect } from 'react';
export default function App() {
const [size, setSize] = useState({ w: window.innerWidth, h: window.innerHeight });
const [lastKey, setLastKey] = useState('(none)');
useEffect(() => {
const onResize = () => setSize({ w: window.innerWidth, h: window.innerHeight });
const onKey = (e) => setLastKey(e.key);
window.addEventListener('resize', onResize);
window.addEventListener('keydown', onKey);
return () => {
window.removeEventListener('resize', onResize);
window.removeEventListener('keydown', onKey);
};
}, []);
return (
<div>
<p>Frame size: {size.w} × {size.h}px (resize your browser)</p>
<p>Click here, then press any key. Last key: <kbd>{lastKey}</kbd></p>
</div>
);
}Fetching data in an effect
Loading data when a prop changes is a classic effect. Use an ignore flag in the cleanup so a slow, outdated response can't overwrite a newer one (a race condition). Here the "server" is simulated with a Promise:
import { useState, useEffect } from 'react';
const BIOS = { ada: 'Wrote the first algorithm (1843).', alan: 'Founded computer science (1936).', grace: 'Built the first compiler (1952).' };
function fakeFetch(id) {
const delay = id === 'ada' ? 1500 : 500; // ada is slow on purpose
return new Promise((resolve) => setTimeout(() => resolve(BIOS[id]), delay));
}
export default function App() {
const [person, setPerson] = useState('alan');
const [bio, setBio] = useState(null);
useEffect(() => {
let ignore = false;
setBio(null);
fakeFetch(person).then((text) => {
if (!ignore) setBio(text);
});
return () => { ignore = true; };
}, [person]);
return (
<div>
{Object.keys(BIOS).map((id) => (
<button key={id} onClick={() => setPerson(id)} disabled={id === person} style={{ marginRight: 4 }}>{id}</button>
))}
<p>{bio ?? 'Loading…'}</p>
<small>Click "ada" then quickly "grace": the slow answer for ada is ignored.</small>
</div>
);
}You might not need an effect
Effects are for synchronizing with things outside React. Many beginner effects are unnecessary:
| Instead of… | Do this |
|---|---|
an effect that sets fullName from first + last |
compute const fullName = first + ' ' + last during render |
| an effect that reacts to a button click | put the logic in the click handler |
| an effect that resets state when a prop changes | give the component a different key |
| an effect to fetch data in a big app | use a framework loader or a data library |
Note: In development,
<StrictMode>mounts every component twice (mount → unmount → mount) to check that your cleanup works. If you see effects run twice locally, that's why — production runs them once. The playgrounds here don't use StrictMode.
Test yourself
When does useEffect(fn, []) run fn?
- Before every render
- After every render
- Once, after the first render
- Never
What is the cleanup function for?
- Resetting state to initial values
- Undoing what the effect set up, before it re-runs and on unmount
- Clearing the console
- Removing the component's DOM
fullName is always first + ' ' + last. Where should you compute it?
- In a useEffect that calls setFullName
- Directly during render
- In componentDidMount
- In a separate state variable updated on every keypress