DEV Community

Michel Billard
Michel Billard

Posted on

Custom React hook to track the mounted status of a component

Have you ever gotten this 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.

As the message implies, you're probably setting state asynchronously in a useEffect hook that you aren't cleaning up properly.

If for some reason you can't cleanup or clear the timeouts properly, you can use the following hook to verify just before setting state if the component is still mounted.

// useIsComponentMountedRef.js
import { useEffect, useRef } from 'react';

const useIsComponentMountedRef = () => {
  const isMounted = useRef(true);

  useEffect(() => {
    return () => {
      isMounted.current = false;
    };
  }, []); // Using an empty dependency array ensures this only runs on unmount

  return isMounted;
};

export default useIsComponentMountedRef;
Enter fullscreen mode Exit fullscreen mode

...and to use it:

import useIsComponentMountedRef from './useIsComponentMountedRef';

const MyComponent = () => {
  const isMountedRef = useIsComponentMountedRef();

  // ex: isMountedRef.current && setState(...)
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)