Function: useMounted()
useMounted(
options?): () =>boolean
Defined in: use-mounted.ts:67
A custom React hook for tracking whether a component is currently mounted.
This hook provides a function that returns the current mount status of the component, which is useful for preventing state updates or async operations after a component has unmounted, thereby avoiding memory leaks and React warnings.
Additionally, this hook supports lifecycle callbacks that can be executed on mount
and unmount. The onMount callback can optionally return a cleanup function,
similar to the return value of useEffect, providing a flexible way to set up
and tear down resources.
This is particularly valuable in scenarios involving asynchronous operations (like API calls or timers) where you need to verify the component is still mounted before updating state with the async result.
Parameters
options?
UseMountedOptions
Optional configuration object:
onMount: Callback invoked when the component mounts. Can return a cleanup function.onUnmount: Callback invoked when the component unmounts.
Returns
A function that returns true if the component is currently mounted,
and false if it has unmounted.
() => boolean
Examples
const isMounted = useMounted();
useEffect(() => {
fetchData().then(data => {
if (isMounted()) {
setData(data);
}
});
}, []);
const isMounted = useMounted({
onMount: () => {
console.log('Component mounted');
const interval = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(interval); // Cleanup function
},
onUnmount: () => {
console.log('Component unmounted');
}
});