Why do I need useEffect? (and what breaks without it)
Why side effects belong after render, and how to avoid infinite loops and stale values
Why Do I Need useEffect? (And What Breaks Without It)
Introduction
Have you ever wondered why you can't just call an API directly inside your React component? Why do we need useEffect at all?
In this article, I explain what useEffect is for, what goes wrong without it, and the mistakes I made while learning it, so you can avoid them.
1. The Problem
A React component is a function that describes what the screen should look like. React calls that function every time something changes, and it may call it many times.
Because of this, a component must be pure: it should only calculate and return UI, and do nothing else.
But real apps need to do more than draw UI. They need to:
Fetch data.
Start timers.
Listen to the browser window.
Change the page title.
These are called side effects: things that reach outside your component.
What happens if you put a side effect straight into the component body?
Take my FetchUser component. Suppose I call fetchUser(id) directly in the body:
function FetchUser() {
const [user, setUser] = useState(null)
fetchUser(id) // Runs on every render
// ...
}Here's what happens:
The component renders and calls the API.
The response arrives and calls
setUser(...).setUsertriggers a re-render, so the API is called again.The loop repeats forever.
The page sends endless requests.
useEffect fixes this by giving side effects a safe place to run: after React has rendered and updated the screen, and only when you ask it to.
2. What Is useEffect?
useEffect is a React hook that lets a component synchronize with something outside React, such as an API, a timer, or the browser.
You give it two things:
A function to run.
A list of values (the dependency array) that tells React when to run it again.
useEffect(() => {
// 1. Setup: do the outside work
return () => {
// 2. Cleanup (optional): undo the setup
}
}, [/* 3. Dependencies */])3. A Minimal Example
Let's create a timer that counts up every second, with a Pause button:
function Timer() {
const [seconds, setSeconds] = useState(0)
const [running, setRunning] = useState(true)
useEffect(() => {
if (!running) return
const timerId = setInterval(() => {
setSeconds((prev) => prev + 1)
}, 1000)
return () => clearInterval(timerId)
}, [running])
return (
<div>
<p>Timer: {seconds}</p>
<button onClick={() => setRunning((r) => !r)}>
{running ? 'Pause' : 'Resume'}
</button>
</div>
)
}Let's break it down:
Setup: Starts a timer.
Cleanup: Stops the timer.
Dependency:
[running]tells React to redo the effect wheneverrunningchanges.
4. How Does It Work?
After every render, React follows this process:
Render the component.
Update the screen (DOM).
The browser paints.
Check the dependency array and run the effect if needed.
React remembers the dependencies from the last render and compares them with the new ones using Object.is.
The effect runs under these conditions:
No dependency array: The effect runs after every render.
Empty dependency array (
[]): The effect runs after the first render only.Dependency array with values (
[a, b]): The effect runs after the first render and again wheneveraorbchanges.
Before React runs an effect again, it first runs the cleanup from the previous run. React also runs the cleanup when the component is removed from the screen.
In the Timer example, this clears the old interval before a new one starts, so timers never pile up.
One more thing: an effect doesn't cause a re-render by itself. Only calling a set... function inside it does.
5. Common Gotchas
1. A Missing Dependency (Stale Closure)
In my Timer, I initially wrote [] as the dependency array and checked if (running) inside the interval.
When I clicked Pause, the timer kept going.
Why?
With [], the effect only ran once, on the first render. The function inside the interval kept the old value running = true forever.
This is called a stale closure: a function that remembers old values from the render it was created in.
Fix: Put running in the dependency array. The effect re-runs when running changes and gets the fresh value.
2. Setting State Inside an Effect That Depends on That Same State
A common mistake is including a state variable in the dependency array while also updating that same state inside the effect.
Here's what happens:
The effect runs.
The effect updates the state.
The state changes, triggering the effect to run again.
The effect updates the state again, repeating the cycle.
This can create an infinite loop.
Fix: Make sure your effect depends on the values that actually trigger the side effect, rather than the state you're updating inside the effect.
3. Forgetting the Cleanup
Without clearInterval, every re-run adds another timer.
With fetch, a slow old response can arrive after a newer one and overwrite the correct data. This is called a race condition.
Fix: Return a cleanup function.
Use
clearIntervalfor timers.Use
removeEventListenerfor event listeners.Use an
AbortControllerfor fetching.
An AbortController is a built-in browser tool that cancels a request.
Example:
useEffect(() => {
const controller = new AbortController()
fetch(url, { signal: controller.signal })
return () => controller.abort()
}, [id])6. When to Use It (And When Not To)
Use useEffect when you need to synchronize with something outside React.
Here are some examples from my practice project:
Fetching data (
FetchUser).Managing a timer (
Timer).Listening to browser events (
WindowSize).Updating
document.title(DocumentTitle).
Don't use useEffect for:
Values you can calculate while rendering. Don't copy state into other state with an effect. Calculate the value directly instead.
Responding to a user action. Put that code in the event handler (such as
onClick) instead.
7. Wrap-Up
Before learning this, I used useEffect simply because I saw it in other people's code.
Now I understand why it exists: rendering has to stay pure, and effects are the safe place for synchronizing with everything outside React.
Here are the three rules I'll remember:
An effect runs after rendering.
The dependency array controls when it runs again.
The cleanup function undoes what the setup did.