Categories
React Answers

How to check if the React component is unmounted?

Spread the love

Sometimes, we want to check if the React component is unmounted.

In this article, we’ll look at how to check if the React component is unmounted.

How to check if the React component is unmounted?

To check if the React component is unmounted, we can use a ref to keep track of the mounted value.

For instance, we write

function MyComponent(props) {
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);

  return <>...</>;
}

export default MyComponent;

to define the isMounted ref with

const isMounted = useRef(false);

Then we add

isMounted.current = true;

in the useEffect to set isMounted.current to true when it’s mounted.

We call useEffect with an empty array so the callback only runs when it’s mounted.

And we return a function that’s called when it’s unmounted in the useEffect callback.

So we set isMounted.current to false there.

Conclusion

To check if the React component is unmounted, we can use a ref to keep track of the mounted value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *