Published:

React - How to Check if a Component is Mounted or Unmounted

This is a quick post to show how to track the mounted status of a React component so you can check if it's mounted or unmounted before performing certain actions.

This is handy if you have a component that performs a state update after a timeout, for example to fade out an alert notification after a few seconds, if the component has been unmounted by the user navigating to a different page, attempting to perform a state update in the timeout function will cause the following error:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.


Track React mounted status with useRef() variable

The useRef() React hook creates a javascript object with a mutable .current property that exists for the lifetime of the component, so it behaves like an instance property which makes it perfect for storing the current mounted status of a React component. The benefit of useRef() over useState() is that updates to the current value of a ref object don't trigger a re-render of the component like state updates do.

Example React component with mounted ref variable

Below is an example component that creates a mounted ref variable with the initial value of false by calling useRef(false). The useEffect() hook is called when the component is mounted and sets the mounted.current value to true. The return function from the useEffect() hook is called when the component is unmounted and sets the mounted.current value to false.

The empty dependency array [] passed as a second parameter to the useEffect() hook causes it to only run once when the component mounts, similar to the componentDidMount() method in a React class component.

import React, { useEffect, useRef } from 'react';

export { ExampleComponent };

function ExampleComponent() {
    const mounted = useRef(false);

    useEffect(() => {
        mounted.current = true;

        return () => {
            mounted.current = false;
        };
    }, []);

    return (
        ...
    );
}

 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some React Help?

Search fiverr to find help quickly from experienced React developers.



Supported by