Lesson 10
25 min
Fetch data from an API, handle loading and clean up effects.
Definition
useEffectis a React hook that allows you to synchronize a component with an external system, generally after it has been rendered. It is used to manage side effects, such as calling an API, starting a timer, listening for an event, or changing the page title. It receives a function containing the effect and, optionally, a dependency array indicating when the effect should run again.
So far, you have learned how to display data, use props, and manage interactions with React. However, some features require communication with elements outside the component: the browser, a server, or a JavaScript timer. This is where useEffect becomes useful.
In this lesson, you will understand how this hook works, learn to manage its dependencies, fetch data from an API, and properly clean up effects. You will also discover situations where it is better not to useuseEffect.
A React component should primarily calculate what it displays based on its props and state. However, it sometimes needs to perform an action beyond this simple calculation: fetching data from a server, changing the browser tab title, or starting a stopwatch. These operations are called side effects.
In programming, a side effect is an action that changes something outside the direct result of a function. For example, a function that calculates a sum normally produces no external effect. On the other hand, a function that sends a network request interacts with another system.
React aims to keep component renderingpredictable. With the same props and state, a component should produce the same result. If you trigger a request directly inside a component's body, it may repeat on every render.useEffect separates these operations from the rendering logic.
body element.Note that actions directly triggered by the user, such as clicking a button or submitting a form, generally do not require useEffect. They should be handled in event handlers such as onClick or onSubmit.
import { useEffect } from "react";
function Example() {
useEffect(() => {
// Code executed after rendering
}, []);
return <p>Hello React!</p>;
}
export default Example;The function passed to useEffectcontains the effect's code. The second argument is adependency array. It tells React which values to monitor to determine whether the effect should run again.
Dependencies are compared with their previous values. If a dependency changes, React first performs any cleanup from the previous effect, then runs the new effect. This behavior keeps the component synchronized with its current values.
To visualize the differences, here are three effects that display messages in the console. Observe what happens during the initial render and after each button click.
import { useEffect, useState } from "react";
function Demo() {
const [count, setCount] = useState(0);
// On mount
useEffect(() => {
console.log("Initial render");
}, []);
// On mount and whenever count changes
useEffect(() => {
console.log("Count:", count);
}, [count]);
// After every render
useEffect(() => {
console.log("A render just occurred");
});
return (
<button onClick={() => setCount(c => c + 1)}>
Clicks: {count}
</button>
);
}
export default Demo;During the initial mount, all three effects run. After each click, the count changes: the second and third effects run again. The first effect does not run again during these updates because its dependency array is empty. In development, StrictModemay cause additional executions to verify that effects are properly cleaned up.
Let's start with a simple effect. Whenever the counter changes, we will update the browser tab title using document.title. Since the effect uses the count value, it must appear in the dependency array.
import { useEffect, useState } from "react";
function TitleCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = "Clicks: " + count;
}, [count]);
return (
<button onClick={() => setCount(c => c + 1)}>
Clicked {count} times
</button>
);
}
export default TitleCounter;
When you click the button, React updates the counter and renders the component again. After this update, the effect changes the browser tab title. The browser therefore displays the same number of clicks as the button. This is an example of synchronization between React state and an external element.
The Dependency Rule
Reactive values used inside the effect, including props, state variables, and variables declared inside the component, must appear in the dependency array. Otherwise, the effect may use outdated values. Tools such as ESLint can detect missing dependencies. Stable values outside the component, such as certain global objects, do not need to be included.
A common use of useEffectis fetching data from a server. For example, an application may load a list of users when it opens. To do this, we generally use the JavaScript fetch() function.
You should handle three situations:loading, while the request is in progress; success, when the data becomes available; and error, when the request fails. Handling these states provides clear feedback to the user.
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Network error");
}
const data = await response.json();
setUsers(data);
} catch (e) {
if (e.name !== "AbortError") {
setError(e.message);
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
load();
return () => controller.abort();
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default Users;Initially, the component displays "Loading...". The effect then starts the request. If the server responds successfully, the data is stored in the users state, which triggers another render. If an error occurs, the corresponding message is displayed.
The AbortController allows the request to be canceled when the component unmounts. This prevents certain unnecessary asynchronous operations from continuing. It is especially useful when requests may take a long time.

Why Not Make the Effect Async?
The function passed directly touseEffect should not be declared async. An asynchronous function returns a Promise, whereas React expects an optional cleanup function. The correct approach is to declare an asynchronous function inside the effect and then call it.
Some data depends on the user's selection. For example, when the user selects another article, the component must load the corresponding information. The dependency array allows this new request to be triggered automatically.
import { useEffect, useState } from "react";
function Article() {
const [id, setId] = useState(1);
const [article, setArticle] = useState(null);
useEffect(() => {
const controller = new AbortController();
setArticle(null);
async function load() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/" + id,
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Article not found");
}
const data = await response.json();
setArticle(data);
} catch (e) {
if (e.name !== "AbortError") {
console.error(e);
}
}
}
load();
return () => controller.abort();
}, [id]);
return (
<div>
<button onClick={() => setId(i => i + 1)}>
Next article
</button>
{article ? (
<h2>{article.title}</h2>
) : (
<p>Loading article...</p>
)}
</div>
);
}
export default Article;With each click, the identifier changes. React detects this change, cleans up the previous effect, and starts a new request. The controller also cancels the previous request, helping to prevent problems when the user clicks quickly.
Some effects start operations that continue running: a timer, a connection, or an event listener. These operations must be stopped when the component unmounts or the effect needs to be recreated. To do this, useEffectcan return a cleanup function.
import { useEffect, useState } from "react";
function Stopwatch() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <p>Elapsed time: {seconds} s</p>;
}
export default Stopwatch;The timer increases the number of seconds every 1,000 milliseconds. The clearInterval() function stops the timer when the effect is cleaned up. Without this cleanup, unnecessary timers could continue running, especially during subsequent mounts.
StrictMode.The same principle applies to browser events. For example, you can monitor the window width to update information on the screen. You must add the event listener when the effect starts and remove it during cleanup.
import { useEffect, useState } from "react";
function WindowWidth() {
const [width, setWidth] = useState(0);
useEffect(() => {
function updateWidth() {
setWidth(window.innerWidth);
}
updateWidth();
window.addEventListener("resize", updateWidth);
return () => {
window.removeEventListener("resize", updateWidth);
};
}, []);
return <p>Window width: {width} px</p>;
}
export default WindowWidth;Whenever the window is resized, the browser triggers the resize event. The updateWidth function then retrieves the new width. When the component unmounts,removeEventListener()removes the listener. Initializing the value to zero also avoids accessing window during possible server-side rendering.
The browser's local storage, called localStorage, allows certain data to be preserved after the page is reloaded. You can use useEffectto save a value whenever it changes.
import { useEffect, useState } from "react";
function SavedCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
localStorage.setItem("count", String(count));
}, [count]);
return (
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
);
}
export default SavedCounter;This example saves the counter whenever it changes. However, it does not yet restore the value when the page loads: the counter is initialized to zero. To truly preserve the counter between visits, you must also read the stored value during initialization. You will encounter this logic again in projects that use local storage.
Understanding StrictMode
In development, React may perform an additional setup and cleanup cycle for effects when using StrictMode. This helps detect cleanup and synchronization problems. You may therefore observe two network requests during development. This verification behavior does not apply in the same way in the production version.
It can be tempting to use useEffectwhenever data changes. However, this hook is not necessary for calculations that can be performed directly during rendering. An unnecessary effect can complicate the component and cause extra renders.
import { useEffect, useState } from "react";
// Avoid
function Profile({ firstName, lastName }) {
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " " + lastName);
}, [firstName, lastName]);
return <h2>{fullName}</h2>;
}// Preferred
function Profile({ firstName, lastName }) {
const fullName = firstName + " " + lastName;
return <h2>{fullName}</h2>;
}The second version is simpler. The full name is calculated immediately from the props, without additional state. It avoids an intermediate render with an outdated value. Remember this rule:if a value can be calculated during rendering, you generally do not need an effect.
function MessageButton() {
function showMessage() {
alert("Hello!");
}
return (
<button onClick={showMessage}>
Show a message
</button>
);
}In this example, the action depends directly on the user's click. It should therefore be executed in the onClick handler, not inside an effect. This distinction makes components easier to understand.
A common mistake is updating state inside an effect that runs after every render. If this update triggers another render every time, the component may enter an infinite loop.
import { useEffect, useState } from "react";
function BadCounter() {
const [number, setNumber] = useState(0);
// Avoid: infinite update loop
useEffect(() => {
setNumber(n => n + 1);
});
return <p>{number}</p>;
}Here, the effect increases the number after every render. This change triggers another render, which runs the effect again, and so on. To avoid this problem, you must identify the actual reason why the state should change. For example, a counter controlled by a button should be updated directly in onClick.
useEffectprimarily to synchronize your component with an external system.useEffect managesside effectsand synchronizes a component with external systems.[]prevents the effect from running again during ordinary component updates.StrictModemay cause additional effect executions during development.useEffect.Exercise
https://jsonplaceholder.typicode.com/posts. Display only the first ten titles. Show a "Loading..." message while the request is in progress and an "Error" message if it fails. Use useEffectand useState, then verify that the list appears after loading.Go Further
AbortControllerto cancel the previous request when a new one starts. Finally, verify that loading and error messages remain correctly displayed.