Home / Learn React / useEffect: Side Effects
useEffect: Side Effects
An effect is code that must run after React has updated the screen: fetching data, setting a timer, changing the page title, listening to events.
Theory in plain words
What it is
useEffect lets you synchronize a component with something outside React: the network, the browser, a timer, a third party library.
Why we use it
Rendering must be pure, so anything that talks to the outside world belongs in an effect or in an event handler. Effects run after the screen is updated, so they never block drawing.
How it works
After each commit React compares the dependency array with the last one. If a value changed (or there is no array) it runs your cleanup from the last effect, then runs the effect. On unmount it runs the final cleanup.
Where it is used
- Fetching data when a page opens
- Setting up and removing timers and event listeners
- Syncing the document title or localStorage
- Connecting to WebSockets and third party widgets
The three forms
| Code | Runs when |
|---|---|
useEffect(fn) | After every render |
useEffect(fn, []) | Once after the first render (and cleanup on unmount) |
useEffect(fn, [a, b]) | After the first render and whenever a or b changed |
Look at the console below the result and at the browser tab title of this page.
Cleanup: stop what you started
When the clock is hidden, cleanup stops the timer. Without it the timer would leak.
Fetch data (and ignore old answers)
If you click fast, the ignore flag stops an old slow response from overwriting the newer one. With a real API use fetch(url, { signal }) and an AbortController.
Dependencies: be honest
Every reactive value that the effect uses (props, state, variables made from them) must be in the dependency array. Do not lie to silence the linter. If the effect reruns too often, change the code, not the array.
useEffect(() => setN(n + 1), [n]).Quick quiz
1. When does useEffect(fn, []) run?
An empty dependency array means "only on mount" (plus cleanup on unmount).
2. What is the cleanup function for?
It runs before the next effect and on unmount.
3. What happens with no dependency array?
Without an array the effect runs after each render.
4. Why use an ignore flag when fetching in an effect?
Cleanup sets ignore when the dependency changes.
Common questions
When does useEffect(fn, []) run?
Once after the first render. An empty dependency array means "only on mount" (plus cleanup on unmount).
What is the cleanup function for?
Undoing the effect: clear timers, remove listeners. It runs before the next effect and on unmount.
What happens with no dependency array?
Runs after every render. Without an array the effect runs after each render.