JAVASCRIPT

React `useIsMounted` Hook for Safe Async Operations

A simple React hook to track if a component is currently mounted, preventing "Can't perform a React state update on an unmounted component" warnings in asynchronous operations.

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

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

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

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

export default useIsMounted;

/* Example Usage:
import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);
  const checkMounted = useIsMounted();

  useEffect(() => {
    const fetchData = async () => {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      if (checkMounted()) {
        setData('Fetched Data!');
      }
    };
    fetchData();
  }, [checkMounted]);

  return <div>{data || 'Loading...'}</div>;
}
*/
How it works: This hook provides a function `checkMounted` that returns `true` if the component is mounted and `false` if it has unmounted. It uses a `useRef` to persist a boolean across renders and `useEffect` to update this ref's value during mount and unmount cycles, effectively preventing state updates on unmounted components after asynchronous operations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs