useIsMounted

Implementation

Check if a React component is mounted

export const useIsMounted = (): boolean => {
  const [isMounted, setIsMounted] = useState(false);
  useEffect(() => {
    setIsMounted(true);

    return () => setIsMounted(false);
  }, []);

  return isMounted;
};

Usage

Don't render anything when not mounted (e.g. on the server in SSG).

const MyComponent = () => {
  const isMounted = useIsMounted();
  
  if (!isMounted) {
    return null;
  }
  
  return (/* ... */ );
}
Last Updated February 27, 2021