Check if the component is still mounted before setState. Prevents memory leak warnings.
import { useRef, useEffect } from 'react';
export function useIsMounted(): () => boolean {
const mounted = useRef(false);
useEffect(() => {
mounted.current = true;
return () => { mounted.current = false; };
}, []);
return () => mounted.current;
}Returns a function that returns true only if the component is still mounted. Call it before setState after async work.
Avoid setState on unmounted component when fetch or timer resolves.
const isMounted = useIsMounted(); fetch(url).then(data => { if (isMounted()) setData(data); });