Categories

Hook10

useIsMounted

Checks if a component is mounted.

Contributed by @itsbrunodev

typescript
import { useEffect, useRef } from "react";
 
function useIsMounted(): () => boolean {
  const isMounted = useRef(true);
 
  useEffect(() => {
    return () => {
      isMounted.current = false;
    };
  }, []);
 
  return () => isMounted.current;
}
typescript
const isMounted = useIsMounted(); // true
GitHubEdit on GitHub