Demystifying React's useEffect Hook
The dependency array doesn't stop your component from re-rendering. It only decides whether the effect runs again after a render.
React is one of the most popular JavaScript libraries for building user interfaces. When building these interfaces, you sometimes need to do things outside of React, such as fetching data from an API, subscribing to browser events, or setting the page title.
That's where the useEffect Hook comes in. It lets you synchronize your component with systems outside of React, after the component renders.
Whether you're new to React or an experienced developer, understanding useEffect is essential, and it's also one of the most misunderstood parts of React. In this article, you'll learn how useEffect works, how dependencies and cleanup really behave, and how to avoid the most common mistakes. The examples are tested with React 19.
What is a side effect in React?#
When working with React components, there are times when you need to interact with something outside of React. These external interactions are known as side effects.
React components should be pure functions: given the same props and state, they return the same JSX, and they don't change anything outside themselves while rendering:
export default function App() {
return <User userName="JaneDoe" />;
}
function User(props) {
return <h1>{props.userName}</h1>; // JaneDoe
}Side effects break that rule because they change something outside the component. Consider an example where you want to change the title of the browser tab to display the user's userName. It might be tempting to do this directly in the component:
const User = ({ userName }) => {
document.title = `Hello ${userName}`; // ❌ Don't do this in the component body
return <h1>{userName}</h1>;
};React may call your component function many times, and at times when the result isn't shown on the screen yet, so code that changes the outside world shouldn't run during rendering. Instead, you put it in an effect, which React runs after the component has rendered and the screen has updated.
Understanding the basics of useEffect#
To use useEffect, import it from react and call it at the top level of your component. It takes two arguments: a setup function and an optional dependency array.
useEffect(() => {
// code that synchronizes with an external system
}, [dependencies]);- The setup function contains the code for your side effect. React runs it after the component first appears on the screen, and again after any re-render where a dependency has changed.
- The dependency array lists the props, state, and other values from your component that the effect uses. React compares them with their values from the previous render to decide whether to run the effect again.
Here's the earlier example, corrected:
import { useEffect } from 'react';
const User = ({ userName }) => {
useEffect(() => {
document.title = `Hello ${userName}`;
}, [userName]);
return <h1>{userName}</h1>;
};The effect runs after the first render and again whenever userName changes. If the component re-renders for another reason, while userName stays the same, the effect doesn't run again.
You may read that useEffect replaces class lifecycle methods like componentDidMount and componentDidUpdate. That comparison can help at first, but React's documentation recommends a different mental model: an effect describes how to start and stop synchronizing with something external, like keeping the page title in sync with userName. Thinking this way makes dependencies and cleanup much easier to get right.
Working with dependencies in useEffect#
The dependency array controls when the effect runs. There are three options:
// 1. Runs after every render
useEffect(() => {
// ...
});
// 2. Runs only after the first render
useEffect(() => {
// ...
}, []);
// 3. Runs after the first render and whenever a or b changes
useEffect(() => {
// ...
}, [a, b]);The rule for the third option is simple: every reactive value the effect uses, meaning props, state, and variables or functions declared in the component, must be in the array. You don't choose dependencies to control when the effect runs. Your code determines them. If an effect runs too often, change the code so it needs fewer dependencies, rather than leaving them out.
The exhaustive-deps rule in the official eslint-plugin-react-hooks package checks this for you and warns about missing dependencies.
How does rendering work in React?#
In React, rendering is when React calls your component to work out what the user interface should look like, based on the current props and state. The first render happens when the component appears on the screen. After that, a change to the component's state, or a re-render of its parent, triggers a new render.
Here's the part that's often misunderstood: the dependency array doesn't stop your component from re-rendering. It only decides whether the effect runs again after a render. Your component still re-renders whenever its state or props change, and React then skips the effect if none of its dependencies changed. If you want to skip re-rendering a component, that's what memo is for, not useEffect.
Cleaning up side effects#
Many effects start something that needs to be stopped later, such as a timer, a subscription, or an event listener. To do that, return a cleanup function from the effect:
useEffect(() => {
// Start something
return () => {
// Stop it
};
}, [dependencies]);React calls the cleanup function at two points:
- Before running the effect again, when a dependency has changed. The cleanup runs with the old values, then the setup runs with the new ones.
- When the component is removed from the screen (unmounted).
React doesn't call the cleanup on every render. For example, with an effect that depends on userId, re-rendering with the same userId runs neither the cleanup nor the setup. Changing userId from 1 to 2 runs the cleanup for 1, then the setup for 2.
Here are two common examples.
1. Clearing intervals#
useEffect(() => {
const interval = setInterval(() => {
// Perform some repeated action
}, 1000);
return () => {
clearInterval(interval);
};
}, []);The cleanup function clears the interval, so it stops running after the component is unmounted.
2. Removing event listeners#
useEffect(() => {
const handleScroll = () => {
console.log(window.scrollY);
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);The cleanup function removes the listener. Without it, every time the component mounts, another listener is added, and old ones keep running after the component is gone.
Why effects run twice in development#
If you use React's Strict Mode, which most new projects enable by default, you may notice that your effect runs twice when the component first mounts: setup, then cleanup, then setup again. This only happens in development. React does it on purpose to check that your cleanup function correctly undoes the setup. If your app works the same after this extra cycle, your effect is set up correctly.
Using the useEffect Hook#
Now let's look at some common, practical uses of useEffect.
1. Fetching data from an external API#
import { useEffect, useState } from 'react';
function Profile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
let ignore = false;
fetch(`https://api.example.com/users/${userId}`)
.then((response) => response.json())
.then((data) => {
if (!ignore) {
setUser(data);
}
});
return () => {
ignore = true;
};
}, [userId]);
return <h1>{user ? user.name : 'Loading...'}</h1>;
}The effect fetches the user whenever userId changes. The ignore flag prevents a race condition. If userId changes from 1 to 2 while the first request is still loading, the cleanup sets ignore to true for the first request. Without it, a slow response for user 1 could arrive after the response for user 2 and overwrite it, so the page would show the wrong user.
For real applications, a data-fetching library such as TanStack Query or your framework's built-in data loading handles this, plus caching and loading states, for you.
2. Saving to localStorage#
import { useEffect, useState } from 'react';
function ThemeToggle() {
const [theme, setTheme] = useState(() => localStorage.getItem('theme') ?? 'light');
useEffect(() => {
localStorage.setItem('theme', theme);
}, [theme]);
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Theme: {theme}
</button>
);
}The initial value is read from localStorage once, when the state is created. The effect then saves the theme whenever it changes, so the user's choice is kept the next time they visit.
3. Updating the document title#
useEffect(() => {
document.title = `${count} new messages`;
}, [count]);Common useEffect errors and how to avoid them#
While working with the useEffect Hook, it's easy to make mistakes that lead to bugs or performance problems. Here are the most common ones and how to fix them.
1. Leaving out the dependency array by accident#
If you leave out the dependency array, the effect runs after every render:
useEffect(() => {
// Runs after every render
});This is valid, and ESLint doesn't warn about it, because sometimes you do want an effect to run after every render. But it's usually a mistake when the effect does something expensive, like fetching data, and it causes an infinite loop if the effect also sets state.
Solution: Add a dependency array that lists the values the effect uses, or [] if it uses none. Don't add an empty array just to make an effect run once if it uses props or state, because that causes the next error.
2. Missing dependencies#
If an effect uses a value but doesn't list it as a dependency, the effect doesn't re-run when that value changes, so it works with an outdated value:
function Profile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`https://api.example.com/users/${userId}`)
.then((response) => response.json())
.then((data) => setUser(data));
}, []); // ❌ userId is missing
}When userId changes, this component keeps showing the first user. ESLint catches it:
React Hook useEffect has a missing dependency: 'userId'. Either include it or remove the dependency array react-hooks/exhaustive-depsSolution: Add every value the effect uses to the dependency array, in this case, [userId]. For a fetch like this one, also add the ignore cleanup shown earlier.
3. Infinite loops#
An infinite loop happens when an effect updates a value that's also one of its dependencies:
const [count, setCount] = useState(0);
useEffect(() => {
setCount(count + 1); // ❌ Updates its own dependency
}, [count]);Each update to count triggers a re-render, the changed dependency runs the effect again, and the effect updates count again, forever. Removing count from the dependencies doesn't fix the real problem. It just turns the loop into an effect that runs once, which is rarely what you wanted.
A more subtle loop comes from objects and arrays created during rendering. A new object is created on every render, so a dependency like this changes every time:
const options = { query, limit: 10 };
useEffect(() => {
// ...
}, [options]); // ❌ A new object on every renderESLint warns about this one too: "The 'options' object makes the dependencies of useEffect Hook change on every render."
Solution: Ask whether you need an effect at all. If you're calculating a value from props or state, do it during rendering instead (see the next section). If the effect does need the object, create it inside the effect, and list the primitive values it uses, such as [query], as dependencies.
4. Forgetting cleanup#
Effects that start timers, subscriptions, or event listeners without stopping them cause memory leaks and bugs, because they keep running after the component is gone:
useEffect(() => {
setInterval(() => {
// Perform some action repeatedly
}, 1000);
// ❌ No cleanup, so the interval keeps running after unmount
}, []);Solution: Return a cleanup function that stops whatever the effect started:
useEffect(() => {
const timer = setInterval(() => {
// Perform some action repeatedly
}, 1000);
return () => {
clearInterval(timer);
};
}, []);Not every effect needs cleanup. Setting the page title, for example, doesn't start anything that has to be stopped.
You might not need an effect#
Many effects in real codebases aren't needed at all. Effects are for synchronizing with things outside React. If you're only working with props and state, there's usually a simpler way:
-
Calculating a value from props or state: Do it during rendering. Instead of storing a
fullNamein state and updating it in an effect, calculate it in the component body:const fullName = `${firstName} ${lastName}`; -
Responding to a user action: Put the code in the event handler. For example, send a form to the server in its
onSubmithandler, not in an effect that watches a "submitted" state. -
Resetting state when a prop changes: Give the component a
key, such as<Profile key={userId} userId={userId} />. React creates a fresh component with fresh state when the key changes.
The latest version of eslint-plugin-react-hooks even warns when you call setState directly in an effect, because it usually means the effect isn't needed. React's guide You Might Not Need an Effect covers many more cases.
Summary#
React's useEffect Hook is the tool for synchronizing your components with systems outside React, such as APIs, browser APIs, timers, and subscriptions. List every value the effect uses as a dependency, return a cleanup function for anything the effect starts, and remember that the dependency array controls when the effect runs, not when the component renders. Before you reach for an effect, check whether you can calculate the value during rendering or handle it in an event handler instead.
When your React app is ready, you can deploy it for free with Sevalla's Static Site Hosting, or use Application Hosting if it needs a server.