UtilityBeginnerSSR-safehooks/utility/useIsMounted.ts

useIsMounted

Stable () => boolean mounted flag.

Import

TypeScript
import { useIsMounted } from '@/hooks';

API

Signature

useIsMounted() → () => boolean

When to use

Use useIsMounted instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Browser utilities are SSR-gated; lifecycle hooks are safe.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useIsMounted
Editor
function SafeAsync() {
  const isMounted = useIsMounted();
  async function load() {
    const data = await fetch('/api/users').then((r) => r.json());
    if (!isMounted()) return;
    console.log(data);
  }
  return <button onClick={() => void load()}>Load</button>;
}
Preview

Implementation source

Full library source for useIsMounted — copy into your project when you are not installing a package yet.

hooks/utility/useIsMounted.ts
import { useCallback, useEffect, useRef } from 'react';

/** Returns a stable function that reports whether the component is mounted. */
export function useIsMounted(): () => boolean {
  const mountedRef = useRef(false);

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

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

Copy-paste example

useIsMounted.example.tsx
'use client';

import { useIsMounted } from '@/hooks';

export function SafeAsync() {
  const isMounted = useIsMounted();
  async function load() {
    const data = await fetch('/api/users').then((r) => r.json());
    if (!isMounted()) return;
    console.log(data);
  }
  return <button onClick={() => void load()}>Load</button>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Lifecycle hooks are for side effects only — not for deriving render state.
  • Source of truth: open hooks/utility/useIsMounted.ts for implementation details