Sub topic 2
Cleanup: Undoing What an Effect Started
Assume you know function components, JSX, useState, JavaScript closures, Promises, and basic fetch. This chapter focuses on effects that connect a component to something outside React.
Cleanup functions
An effect may start a subscription, timer, event listener, or network request. Its cleanup function undoes that work. React runs cleanup before the effect runs again and when the component unmounts.
useEffect(() => {
const id = setInterval(() => {
console.log('tick');
}, 1000);
return () => clearInterval(id);
}, []);The empty dependency array means this effect starts once for the component’s lifetime. Cleanup still matters because the component may be removed.
Event listeners, subscriptions, and timers
Listeners and subscriptions must be removed with the same function reference used to add them.
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);Timers need clearInterval or clearTimeout. Without cleanup, old callbacks can continue running and update an unmounted component or duplicate work.
> callout note > Cleanup should be the inverse of setup. If setup adds, starts, or subscribes, cleanup should remove, stop, or unsubscribe.
Fetching data and avoiding race conditions
When a prop changes, an earlier request may finish after a newer request. Abort the previous request during cleanup.
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((response) => response.json())
.then(setUser)
.catch((error) => {
if (error.name !== 'AbortError') setError(error);
});
return () => controller.abort();
}, [userId]);The dependency array makes userId part of the effect’s synchronization. Cleanup prevents a stale response from winning.
Effect or event handler?
Use an event handler for work caused directly by an interaction, such as submitting a form or sending analytics for a button click. Use an effect when rendering commits a synchronization with an external system.
When you do not need an effect
Do not use an effect to calculate a value from props or state. Calculate it during rendering instead. This avoids an extra render and prevents copied state from becoming outdated.
function FilteredList({ items, query }) {
const visible = items.filter((item) => item.name.includes(query));
return <ul>{visible.map((item) => <li key={item.id}>{item.name}</li>)}</ul>;
}Exercise
What should cleanup do for an effect that calls setInterval?
Show answer
Call clearInterval with the interval ID returned by setInterval.