Description

Sometimes we don't want to do an action until a component is mounted. We can do this by checking if a useEffect has been called.
?

Reach for when

You need to prevent state updates on unmounted components.

Code

function useIsMounted() {
  const isMounted = useRef(false);
  useEffect(() => {
    isMounted.current = true;
    return () => { isMounted.current = false; };
  }, []);
  return useCallback(() => isMounted.current, []);
}