useEffect Cleanup

Learn how to clean up side effects to prevent memory leaks and errors.

The cleanup function in useEffect prevents errors on unmounted components.

The Problem

If a component unmounts before a fetch completes, React tries to update state on an unmounted component — causing an error.

The Fix — AbortController

useEffect(() => {
  const abortCont = new AbortController();

  fetch(url, { signal: abortCont.signal })
    .then(res => res.json())
    .then(data => setData(data))
    .catch(err => {
      if (err.name !== "AbortError") {
        setError(err.message);
      }
    });

  // Cleanup function
  return () => abortCont.abort();
}, [url]);

The cleanup runs when the component unmounts or before the effect re-runs.