Course contentsShow
← React
Lesson 576 of 2,39616. useEffect for Data FetchingFree lesson

Basic Cleanup with Boolean Flags

Use a boolean flag in the cleanup function to prevent setting state after the component unmounts.

Basic Cleanup with Boolean Flags

What you'll learn: How to use a simple boolean flag in your cleanup function to prevent setting state after a component has unmounted.

The Problem Recap

In the previous lesson, you learned that calling setState after a component unmounts triggers a React warning. This commonly happens when a fetch completes after the user has navigated away or the component has been removed from the page.

The Boolean Flag Solution

The simplest fix is to create a boolean variable inside your effect that tracks whether the component is still mounted. Return a cleanup function that sets this flag to false, and check the flag before calling setState:

useEffect(() => {
  let isMounted = true;

  fetch('/api/data')
    .then(res => res.json())
    .then(data => {
      if (isMounted) {
        setData(data);
      }
    });

  return () => {
    isMounted = false;
  };
}, []);

How It Works

When the component unmounts, React calls your cleanup function, which flips isMounted to false. If the fetch completes afterward, the if (isMounted) check prevents the setState call. The fetch still finishes in the background (you can't truly cancel it with this approach), but you safely ignore the result.

Think of it like: A delivery driver who checks "is this house still expecting a package?" before ringing the doorbell. If the residents moved out, the driver doesn't try to deliver.

Why This Works

Each render creates a new isMounted variable in its own closure. The cleanup function and the .then() callback both close over the same isMounted reference, creating a communication channel between them.

Key Takeaway: Use a boolean flag (isMounted) and a cleanup function to prevent state updates after unmount—check the flag before every setState call in async code.