A hook to track if a component is still mounted.
import { useEffect, useRef } from 'react';
export function useIsMounted() {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
}In React, it's important to avoid updating state or performing actions after a component has unmounted — especially when dealing with asynchronous operations like API calls or timeouts.
The useIsMounted hook helps you safely check if the component is still mounted before proceeding.
import { useEffect, useRef } from 'react';
export function useIsMounted() {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
}
function Profile() {
const isMounted = useIsMounted();
const [data, setData] = useState(null);
useEffect(() => {
fetchUserProfile().then((result) => {
if (isMounted.current) {
setData(result);
}
});
}, []);
return <div>{data ? data.name : "Loading..."}</div>;
}
This prevents trying to update state on an unmounted component — which would otherwise throw a warning in development mode.
The useIsMounted hook is a simple yet powerful way to avoid common React pitfalls — especially useful in cleanup-heavy or async-heavy components.