DEV Community

Michel Billard
Michel Billard

Posted on

2 1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay