HooksuseIsMounted

useIsMounted()

The useIsMounted() hook allows you to check if a component is still mounted before performing state updates or side effects. This is particularly useful for avoiding memory leak warnings in asynchronous operations.

Import

typescript
import { useIsMounted } from 'the-react-hooks';

Usage

1. Start the delay inside the component.
2. Quickly toggle visibility to "Unmount" it.
3. Check console logs to see the safety check in action.

Async StatusIdle
Component.tsx
import { useIsMounted } from 'the-react-hooks';
import { useState, useEffect } from 'react';

export const Component = () => {
  const isMounted = useIsMounted();
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('/api/data').then((response) => {
      if (isMounted()) {
        setData(response);
      }
    });
  }, []);

  return <div>{data ? 'Loaded' : 'Loading...'}</div>;
}

API

Arguments

This hook does not accept any arguments.

Returns

Returns a function:
  • checkIsMounted () => boolean A function that returns true if the component is mounted, and false otherwise.