Sub topic 12
When You Do Need an Effect: Fetching Data Safely
This chapter assumes you know function components, useState, and the basics of useEffect and its dependency array. You also need to know that React re-renders a component when its state or props change.
The earlier chapters showed many cases where an Effect is unnecessary. Here is the opposite case. An Effect is the right tool when a component must synchronize with a system outside React because the component is displayed. Fetching data for a search box is one example. The fetch is not caused by one click. It is caused by the component showing a particular query.
Why fetching belongs in an Effect
Ask what caused the work. A form submission is caused by a user click, so it belongs in an event handler. Search results for the current query are caused by the component being on screen with that query. The query can change by typing, by navigation, or by a parent re-rendering. No single event covers all of those. An Effect covers them because it re-synchronizes whenever its dependencies change.
A first version and its bug
This version looks reasonable, but it has a race condition.
import { useState, useEffect } from 'react';
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
fetch('/api/search?q=' + encodeURIComponent(query))
.then(response => response.json())
.then(json => setResults(json));
}, [query]);
return (
<ul>
{results.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}Suppose the user types "re" and then "react". Two requests start. Network responses can arrive in any order. If the response for "re" arrives last, setResults stores results for "re" while the input shows "react". The screen is now wrong, and nothing in the code reports an error.
Fixing it with cleanup
React runs an Effect's cleanup function before it runs the Effect again, and when the component unmounts. You can use the cleanup to mark the earlier request as stale.
import { useState, useEffect } from 'react';
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
let ignore = false;
fetch('/api/search?q=' + encodeURIComponent(query))
.then(response => response.json())
.then(json => {
if (!ignore) {
setResults(json);
}
});
return () => {
ignore = true;
};
}, [query]);
return (
<ul>
{results.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}Each run of the Effect creates its own ignore variable. When query changes, React calls the previous run's cleanup, which sets that run's ignore to true. If the old response arrives later, it is dropped. Only the response from the latest run can update state.
The sequence looks like this.
Common errors
- Forgetting a dependency. If
queryis missing from the array, the Effect never re-runs when it changes, and the results go stale. - Skipping cleanup. Without it, the race condition described above returns.
- Fetching in an event handler when the data depends on displayed state. If the data must match what is on screen, an Effect keeps the two in sync. If the work is a one-time reaction to a click, such as posting a form, use the handler.
- Being surprised by double requests in development. In Strict Mode, React runs Effects twice on mount to check that cleanup works. This happens only in development. A correct cleanup makes the extra run harmless.
Frameworks and libraries
Writing this by hand in every component is repetitive. You also have to handle loading states, errors, and caching yourself. Many frameworks and data-fetching libraries do this for you. A custom Hook that wraps the Effect above keeps your components simple and puts the cleanup logic in one place.
Exercise
A component fetches user details in an Effect that depends on [userId]. A user clicks quickly through three profiles, and sometimes the page shows details for the wrong user. What is the cause, and what is the fix?
Show answer
Responses can arrive out of order, so an older request can finish last and overwrite the state with the wrong user's data. Fix it by adding a cleanup function that sets a per-run ignore flag to true, and check !ignore before calling the state setter.
Exercise
Should a request that posts a registration form when the user clicks "Register" be in an Effect or an event handler? Why?
Show answer
In an event handler. The click caused the work, so the handler is the right place. An Effect would run in response to a state change, which makes the logic harder to follow and can run it at the wrong times.