Effects
useIsMounted
A stable getter for whether the component is still mounted.
Demo
live · imported from hookli
child mounted
- status
- idle
- result
- —
- guarded skips
- 0
Start the task, then unmount before it resolves — the update is skipped, not warned. Leave it mounted and the result lands as usual.
import { useIsMounted } from "hookli";
export function Demo() {
const isMounted = useIsMounted();
async function load() {
const data = await fetchData();
if (isMounted()) setData(data);
}
return <button onClick={load}>Load</button>;
}Usage
import { useIsMounted } from "hookli";
export function Demo() {
const isMounted = useIsMounted();
async function load() {
const data = await fetchData();
if (isMounted()) setData(data);
}
return <button onClick={load}>Load</button>;
}API
useIsMounted(): () => booleanParameters
This hook takes no parameters.
Returns
| Name | Type | Description |
|---|---|---|
| isMounted | () => boolean | A stable getter that returns true while mounted and false after unmount. Call it inside async callbacks before setting state; its identity never changes, so it is safe to omit from dependency arrays. |
Hook
The implementation, straight from hookli. Copy it, or install the package.
import { useCallback, useEffect, useRef } from "react";
export const useIsMounted = () => {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return useCallback(() => isMounted.current, []);
};