JAVASCRIPT
React Hook: useIsMounted for Preventing State Updates on Unmounted Components
Create a React hook `useIsMounted` to track if a component is currently mounted, effectively preventing "Can't perform a React state update on an unmounted component" warnings in asynchronous operations.
import { useRef, useEffect, useCallback } from 'react';
const useIsMounted = () => {
const isMountedRef = useRef(true);
useEffect(() => {
return () => {
isMountedRef.current = false;
};
}, []);
const getIsMounted = useCallback(() => isMountedRef.current, []);
return getIsMounted;
};
export default useIsMounted;
How it works: The `useIsMounted` hook provides a way to check if a component is still mounted during asynchronous operations. It uses a `useRef` to maintain a mutable boolean value, initialized to `true`. The `useEffect` hook's cleanup function sets this ref's value to `false` when the component unmounts. The hook returns a `useCallback` wrapped function `getIsMounted` that can be called to check the current mount status, preventing common "Can't perform a React state update on an unmounted component" errors.