sr✳SHUBHAM RAJFRONTEND ENGINEER
FULL TECHNICAL GUIDEFoundation3 min read

When should a React effect return a cleanup function?

Return cleanup when an effect sets up subscriptions, timers, listeners, or cancelable work.

React#effects#cleanup
THE ANSWER / PLAIN ENGLISH

The idea to remember.

Return cleanup when an effect sets up subscriptions, timers, listeners, or cancelable work. React runs cleanup before relevant effect reruns and when the component unmounts.

From first example to real project.

Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.

Basic: local state

01 / BEGINNER

Update React state without mutating the previous value.

JSX / EXAMPLE
function Counter() {
  const [count, setCount] = React.useState(0);
  return <button onClick={() => setCount(n => n + 1)}>{count}</button>;
}

Intermediate: synchronize external data

02 / INTERMEDIATE

An effect subscribes to something outside React and cleans it up.

JSX / EXAMPLE
function OnlineStatus() {
  const [online, setOnline] = React.useState(navigator.onLine);
  React.useEffect(() => {
    const update = () => setOnline(navigator.onLine);
    window.addEventListener('online', update);
    window.addEventListener('offline', update);
    return () => {
      window.removeEventListener('online', update);
      window.removeEventListener('offline', update);
    };
  }, []);
  return <p>{online ? 'Online' : 'Offline'}</p>;
}

Real scenario: cancel stale requests

03 / REAL SCENARIO

Cancel the previous request when a search term changes.

JSX / EXAMPLE
React.useEffect(() => {
  const controller = new AbortController();
  fetch('/api/search?q=' + encodeURIComponent(query), { signal: controller.signal })
    .then(response => { if (!response.ok) throw new Error('Request failed'); return response.json(); })
    .then(setResults)
    .catch(error => { if (error.name !== 'AbortError') setError(error.message); });
  return () => controller.abort();
}, [query]);

Try it in your own words.

Explain when should a React effect return a cleanup function without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.

Keep learning here.

Explore more in-depth guides, exercises and related interview questions in this library.

Browse React study guides ↗
← Back to question library

Have something
in mind?

Start a conversation