Join our Discord Community

useIsMounted

Prevent memory leaks by checking component mount state before async operations. Perfect for React applications requiring safe state updates with Next.js integration and TypeScript support.

Loading component...

Installation

npx shadcn@latest add https://www.shadcn.io/registry/use-is-mounted.json
npx shadcn@latest add https://www.shadcn.io/registry/use-is-mounted.json
pnpm dlx shadcn@latest add https://www.shadcn.io/registry/use-is-mounted.json
bunx shadcn@latest add https://www.shadcn.io/registry/use-is-mounted.json

Features

  • Memory leak prevention by checking mount state before setState operations
  • Async operation safety preventing updates on unmounted components
  • Zero dependencies using only native React hooks (useRef, useEffect, useCallback)
  • TypeScript support with complete type definitions and function return types
  • Performance optimized with memoized function reference using useCallback
  • shadcn/ui integration compatible with component lifecycle management

Examples

Component Lifecycle Management

Loading component...

Multiple components with different async delays demonstrating safe state updates.

Use Cases

This free open source React component works well for:

  • API calls - Prevent state updates after component unmounts with Next.js and TypeScript
  • Timers and intervals - Safe cleanup of async operations using React hooks
  • File uploads - Cancel operations when components unmount with proper error handling
  • WebSocket connections - Prevent memory leaks in real-time applications

API Reference

useIsMounted

ParameterTypeDescription
None-Hook takes no parameters

Return Value

TypeDescription
() => booleanFunction that returns true if component is mounted, false otherwise

Usage Pattern

import { useIsMounted } from '@repo/use-is-mounted';

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

  useEffect(() => {
    fetchData().then(result => {
      if (isMounted()) {
        setData(result); // Safe: only updates if still mounted
      }
    });
  }, [isMounted]);

  return <div>{data}</div>;
}

Implementation Notes

  • Returns a stable function reference that won't cause unnecessary re-renders
  • Uses useRef to track mount state without triggering component updates
  • Cleanup function automatically sets mounted state to false on unmount
  • Compatible with React Strict Mode and concurrent features
  • Prevents React warnings about setState calls on unmounted components
  • Works with any async operation including promises, timeouts, and intervals