State Management
useGetIsMounted
About
A hook that provides a way to check if a component is currently mounted. This is particularly useful for preventing state updates on unmounted components, especially after asynchronous operations like API calls, timers, or promises. The hook returns a function that returns a boolean indicating the current mount status.
Examples
Basic usage
Preventing state updates after async operations
Using with timers and intervals
Alternative: Using useSafeSetState
For a more convenient approach to safe state updates, you can use the useSafeSetState
hook from our collection, which internally uses useGetIsMounted
to provide a drop-in replacement for useState
that automatically prevents updates on unmounted components:
Arguments
This hook doesn't accept any arguments.
Returns
Return value | Type | Description | Default |
---|---|---|---|
getIsMounted | Function | A function that returns a boolean indicating if the component is currently mounted | undefined |
Return Function
The returned getIsMounted
function:
Return value | Type | Description |
---|---|---|
isMounted | Boolean | true if the component is mounted, false otherwise |
Use Cases
- Async Operations: Prevent state updates after API calls, file uploads, or other async operations complete
- Timers and Intervals: Avoid memory leaks and errors from timers that continue after component unmount
- Event Listeners: Clean up event listeners and prevent handlers from running on unmounted components
- Promises and Callbacks: Ensure promise resolutions and callback executions don't affect unmounted components
- Conditional Rendering: Make decisions based on component mount status in complex scenarios
Notes
- The hook uses a
useRef
to track mount status, which persists across re-renders - The mount status is set to
true
inuseEffect
andfalse
in the cleanup function - This pattern helps prevent the common React warning: "Can't perform a React state update on an unmounted component"
- For simpler use cases, consider using
useSafeSetState
which provides the same safety with a more convenient API