useHooks.iov4.1.2
DocsBlogGitHub
Hooks
No hooks found in any category.

useIsMounted

utility

Installation

npx usehooks-cli@latest add use-is-mounted

Description

A React hook that provides a function to check whether the component is currently mounted. Useful for preventing state updates on unmounted components and avoiding memory leaks.

Examples

Basic Usage

Checking mount status before state updates

1const isMounted = useIsMounted(); 2 3const fetchData = async () => { 4 try { 5 const response = await fetch('/api/data'); 6 const data = await response.json(); 7 8 // Only update state if component is still mounted 9 if (isMounted()) { 10 setData(data); 11 } 12 } catch (error) { 13 if (isMounted()) { 14 setError(error.message); 15 } 16 } 17};

Preventing Memory Leaks

Using with async operations to prevent warnings

1const isMounted = useIsMounted(); 2const [loading, setLoading] = useState(false); 3const [data, setData] = useState(null); 4 5const handleAsyncOperation = useCallback(async () => { 6 setLoading(true); 7 8 try { 9 await new Promise(resolve => setTimeout(resolve, 2000)); 10 11 // Check if component is still mounted before updating state 12 if (isMounted()) { 13 setData('Operation completed'); 14 setLoading(false); 15 } 16 } catch (error) { 17 if (isMounted()) { 18 setLoading(false); 19 } 20 } 21}, [isMounted]);

With useEffect Cleanup

Combining with useEffect for safe async operations

1const isMounted = useIsMounted(); 2 3useEffect(() => { 4 let cancelled = false; 5 6 const fetchUserData = async () => { 7 try { 8 const response = await fetch(`/api/users/${userId}`); 9 const userData = await response.json(); 10 11 // Double check: not cancelled and component still mounted 12 if (!cancelled && isMounted()) { 13 setUser(userData); 14 } 15 } catch (error) { 16 if (!cancelled && isMounted()) { 17 setError(error.message); 18 } 19 } 20 }; 21 22 fetchUserData(); 23 24 return () => { 25 cancelled = true; 26 }; 27}, [userId, isMounted]);

Dependencies

react

Notes

  • Returns a function, not a boolean value directly - call the function to get the current mount status
  • Uses useRef to track mount status without causing re-renders
  • Particularly useful for preventing 'Can't perform a React state update on an unmounted component' warnings
  • Should be used in combination with proper cleanup patterns in useEffect
  • The returned function is stable and doesn't change between renders
  • Helps prevent memory leaks in async operations like API calls or timers

Implementation

1"use client"; 2 3import { useEffect, useRef } from "react"; 4 5export function useIsMounted(): () => boolean { 6 const isMountedRef = useRef(false); 7 8 useEffect(() => { 9 isMountedRef.current = true; 10 11 return () => { 12 isMountedRef.current = false; 13 }; 14 }, []); 15 16 return () => isMountedRef.current; 17} 18 19export default useIsMounted; 20