Show contents
Chapter 4 of 6 · 20 min
Effects and data loading
By the end of this chapter, you'll be able to
- Explain what an effect is and when it runs
- Load data with useEffect and fetch
- Handle the three states of a load: in progress, succeeded, failed
- Avoid updates after a page change or a stale response
Rendering and effects
A component's function must stay pure: it computes the display from props and state, without changing anything elsewhere. Anything that acts on the outside world (calling an API, starting a timer, writing to the browser's storage) is a side effect, and goes into useEffect:
import { useEffect, useState } from "react";
function Catalogue() {
const [state, setState] = useState({ status: "loading", courses: [], error: null });
useEffect(() => {
let cancelled = false;
fetch("/api/courses")
.then((response) => {
if (!response.ok) throw new Error(`error ${response.status}`);
return response.json();
})
.then((courses) => { if (!cancelled) setState({ status: "ready", courses, error: null }); })
.catch((e) => { if (!cancelled) setState({ status: "error", courses: [], error: e.message }); });
return () => { cancelled = true; };
}, []);
if (state.status === "loading") return <p role="status">Loading courses…</p>;
if (state.status === "error") return <p role="alert">Could not load the courses ({state.error}).</p>;
return <CourseList courses={state.courses} />;
}
- the dependency array
[], as second argument, says when to rerun the effect: empty, it only runs after the first display;[search]would rerun it wheneversearchchanges; - the returned function (
return () => { cancelled = true; }) is the cleanup: React calls it when the component disappears or before rerunning the effect; fetchdoes not throw for a 404 or 500 code: you must testresponse.okyourself.
The new state triggers a render: the cards replace the message. On error, a clear message is shown instead.
Text description of the animation
- The component first displays with the initial state: nothing has arrived yet.
- After this first display, React runs the effect, which sends the request.
- The interface stays usable while waiting: the page is never blocked.
- The response arrives: the effect updates the state with setState.
- The new state triggers a render: the cards replace the message. On error, a clear message is shown instead.
Simulating the API to understand
To understand the order of events without a server, let's simulate an API that answers after a delay, with a promise:
function fakeApi(fail) {
return new Promise((resolve, reject) => {
setTimeout(() => (fail ? reject(new Error("network unavailable")) : resolve(["Python", "SQL", "IP networks"])), 50);
});
}
async function load(fail) {
console.log("state: loading");
try {
const courses = await fakeApi(fail);
console.log("state: ready,", courses.length, "courses");
} catch (e) {
console.log("state: error,", e.message);
}
}
await load(false);
await load(true);
state: loading
state: ready, 3 courses
state: loading
state: error, network unavailable
await waits for the promise without blocking the page; try / catch catches the error. The two await lines at the bottom of the program wait for each load to finish before starting the next. This is exactly the logic of the component's effect, written with async / await.
Thinking about slow connections
- Show a loading state immediately, and keep the page usable.
- Provide a "Try again" button on error, rather than a blank page.
- Only load what is displayed (one page of results at a time), and avoid firing a request on every keystroke: wait for example 300 ms without a new keystroke before searching.
Mini-lab: loading with retriesJavaScript
Output
Click “Run” to execute your code.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: a loading reducer
Write a pure function reduce(state, action) that computes the new state of a load from an action: { type: "start" }, { type: "success", courses } or { type: "failure", message }. Check the sequence start → failure → start → success.
Hint 1
switch (action.type) with one case per action type.Hint 2
{ status, courses, error }.Show the solution and common mistakes
function reduce(state, action) {
switch (action.type) {
case "start":
return { ...state, status: "loading", error: null };
case "success":
return { status: "ready", courses: action.courses, error: null };
case "failure":
return { ...state, status: "error", error: action.message };
default:
return state;
}
}
let state = { status: "idle", courses: [], error: null };
for (const action of [
{ type: "start" },
{ type: "failure", message: "network unavailable" },
{ type: "start" },
{ type: "success", courses: ["Python", "SQL"] },
]) {
state = reduce(state, action);
console.log(action.type.padEnd(7), "→", state.status, state.error ?? "", state.courses.length);
}
start → loading 0
failure → error network unavailable 0
start → loading 0
success → ready 2
This function can be used directly with React's useReducer hook: const [state, dispatch] = useReducer(reduce, initialState), then dispatch({ type: "start" }).
Common mistakes:
- Forgetting to reset
errortonullat the start of a new load: the old error message stays displayed while the courses arrive. - Modifying
statedirectly in the reducer (state.status = …): as withuseState, React would not see the change.
Summary
- 1A component's function stays pure; API calls and other side effects go into useEffect.
- 2The dependency array says when to rerun the effect; the returned function does the cleanup.
- 3A load has three states to display: in progress, succeeded, failed.
- 4fetch does not throw for a 404 or a 500: test response.ok.
- 5The cleanup lets you ignore a stale response when the search has changed.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.