avatar

Le Do Nghiem

Software Engineer

  • About me
  • Books
  • Snippets
  • Blog

© 2026 Le Do Nghiem. All rights reserved.

Contact |

Back to Snippets

useIsMounted Hook

A hook to track if a component is still mounted.

LanguageTypeScript
Last UpdatedApr 21, 2025
use-is-mounted.ts
import { useEffect, useRef } from 'react';

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

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

  return isMounted;
}

In React, it's important to avoid updating state or performing actions after a component has unmounted — especially when dealing with asynchronous operations like API calls or timeouts.

The useIsMounted hook helps you safely check if the component is still mounted before proceeding.

import { useEffect, useRef } from 'react';

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

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

  return isMounted;
}

How It Works

  • useRef(false) initializes a persistent reference to track mounted state.
  • When the component mounts, isMounted.current = true.
  • On unmount, the cleanup function sets isMounted.current = false.
  • You can access isMounted.current anywhere to check the mount status.

Example Usage

function Profile() {
  const isMounted = useIsMounted();
  const [data, setData] = useState(null);

  useEffect(() => {
    fetchUserProfile().then((result) => {
      if (isMounted.current) {
        setData(result);
      }
    });
  }, []);

  return <div>{data ? data.name : "Loading..."}</div>;
}

This prevents trying to update state on an unmounted component — which would otherwise throw a warning in development mode.

Use Cases

  • Handling async calls safely in useEffect
  • Cancelling timers or animation callbacks
  • Preventing memory leaks
  • Working with subscriptions or external events

Notes

  • This hook does not stop the effect from running. It only provides a flag to check status.
  • Avoid accessing isMounted.current directly in render — only in effects or callbacks.

The useIsMounted hook is a simple yet powerful way to avoid common React pitfalls — especially useful in cleanup-heavy or async-heavy components.

Previous Snippet

useDebounce Hook

Next Snippet

useToggle Hook