JavaScript Snippet

React useIsMounted Hook

Difficulty: Easy

Setting state on an unmounted component throws a warning in development and can mask real bugs in production. The useIsMounted hook gives async callbacks a way to bail out before they touch React state. This snippet covers the basic ref-based hook, a useSafeState wrapper that no-ops after unmount, and a useSafeCallback variant that protects the function itself.

Code Snippets
/

React useIsMounted Hook

React useIsMounted Hook

Setting state on an unmounted component throws a warning in development and can mask real bugs in production. The useIsMounted hook gives async callbacks a way to bail out before they touch React state. This snippet covers the basic ref-based hook, a useSafeState wrapper that no-ops after unmount, and a useSafeCallback variant that protects the function itself.

JavaScript
Easy
3 snippets
react
hooks
code-template
references

656 views

14

The hook returns a stable function that returns whether the component is currently mounted. Storing the flag in a ref keeps reads cheap and avoids triggering re-renders. The cleanup callback in useEffect is what flips the flag false on unmount, and returning a function (not the ref directly) lets call sites read the latest value at the moment they need it. Use it as if (!isMounted()) return; inside async callbacks before calling any setter.