JAVASCRIPT

React useIsMounted Hook for Safe State Updates

Create a `useIsMounted` React hook to track a component's mount status, preventing state updates on unmounted components and avoiding memory leaks.

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

function useIsMounted() {
  const isMounted = useRef(false);

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

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

  const getIsMounted = useCallback(() => isMounted.current, []);

  return getIsMounted;
}
How it works: The `useIsMounted` hook provides a way to check if a component is currently mounted, which is crucial for preventing memory leaks and errors when performing asynchronous operations. It uses a `useRef` to maintain a mutable boolean flag. The `useEffect` sets this flag to `true` on mount and returns a cleanup function to set it to `false` on unmount. A `useCallback` memoizes a getter function, ensuring consistent access to the current mount status without causing re-renders, making it safe to use in async callbacks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs