useEffect()
useEffect is the React hook for running code that reaches outside the component's rendering, known as a side effect. Fetching data from an API is the classic example: rendering should only describe what to show, while the request itself belongs in an effect that runs after React has updated the screen. Other effects include setting up timers, subscribing to events and updating the document title.
How useEffect is called
The hook takes two arguments: a function containing the effect, and a dependency array. React runs the function after the first render, and then again only when one of the listed dependencies has changed since the previous render. The function may return a cleanup function, which React calls before running the effect again and when the component is removed.
| Dependency array | When the effect runs |
|---|---|
| Not provided | After every render |
[] | Once, after the component first appears |
[userId] | After the first render and whenever userId changes |
Fetching data when a component loads
The effect function itself cannot be async, because React expects it to return either nothing or a cleanup function, not a promise. Define an async function inside and call it.
import { useEffect, useState } from 'react';
function UserPosts({ userId }) {
const [posts, setPosts] = useState([]);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const controller = new AbortController();
async function loadPosts() {
setLoading(true);
setError(null);
try {
const res = await fetch(`/api/users/${userId}/posts`, {
signal: controller.signal
});
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
setPosts(await res.json());
} catch (err) {
if (err.name !== 'AbortError') setError(err.message);
} finally {
setLoading(false);
}
}
loadPosts();
return () => controller.abort(); // cancel if userId changes or we unmount
}, [userId]);
if (loading) return <p>Loading posts...</p>;
if (error) return <p>Error: {error}</p>;
return <ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>;
}
Why the cleanup matters for requests
If the user switches quickly from one profile to another, two requests may be in flight. Without cleanup, the slower first response could arrive last and overwrite the correct data with the wrong user's posts. Aborting the old request in the cleanup function removes this race. In development, React's Strict Mode mounts components, unmounts them and mounts them again, so you will see the effect run twice; correct cleanup makes that harmless.
Not every task belongs in an effect. Values you can calculate from props or state during rendering, such as a filtered list or a total, should simply be computed in the component body. Putting them in an effect with an extra state variable causes an unnecessary second render and can show stale values for a moment. As projects grow, many teams also move data fetching into a dedicated library or a framework loader, which handles caching and retries, but the pattern here is what those tools do underneath.
The infinite loop trap
Calling a state setter inside an effect that has no dependency array causes a loop: the effect sets state, state triggers a render, the render triggers the effect again. A similar loop happens when a dependency is an object or array created fresh on every render, since React compares dependencies by reference. Keep dependencies to primitive values like IDs where you can, and include every value from the component that the effect reads, as the React lint rule recommends.
What to remember
- Put requests in effects, not directly in the component body.
- List every value the effect uses in the dependency array.
- Return a cleanup that aborts stale requests.
- Track loading and error state alongside the data.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.