useIsMounted
import { useEffect, useRef } from 'react';export const useIsMounted = () => { const isMounted = useRef(false); useEffect(() => { isMounted.current = true; return () => { isMounted.current = false; }; }, []); return isMounted;};
The useIsMounted
hook is a custom React hook that allows you to check if a component is currently mounted. This can be useful in scenarios where you want to avoid updating the state of an unmounted component, which can lead to memory leaks or errors.
The hook uses a useRef
to keep track of the mounted state and a useEffect
to set the mounted state to true
when the component mounts and false
when it unmounts. The returned value is a reference that can be used to check if the component is still mounted.
This is particularly useful in asynchronous operations, such as API calls or timers, where you want to ensure that the component is still mounted before attempting to update its state.