useSafeSetState
About
A hook that provides a safe version of useState
that prevents state updates after the component has unmounted. This is particularly useful for async operations to avoid memory leaks and React warnings.
Examples
Basic example
Example with fetch operation
Example with functional state updates
Arguments
Argument value | Type | Description | Default |
---|---|---|---|
initialState | T | The initial state value | undefined |
Returns
Returns an array with two elements:
Return value | Type | Description | Default |
---|---|---|---|
state | T | The current state value | undefined |
safeSetState | Dispatch<SetStateAction<T>> | Function to update state, but only if component is still mounted | undefined |
Behavior
The useSafeSetState
hook behaves identically to React's built-in useState
hook with one important difference: the setter function (safeSetState
) will only update the state if the component is still mounted.
This prevents:
- Memory leaks from async operations
- React warnings about setting state on unmounted components
- Unnecessary state updates that won't affect the UI
The hook internally uses useGetIsMounted
to check if the component is still mounted before allowing state updates.
Use Cases
- Async API calls: Prevent state updates from completed requests after navigation
- Timers and intervals: Avoid state updates from delayed operations
- Event handlers: Safe state updates in long-running event callbacks
- Cleanup-sensitive operations: Any operation that might complete after component unmount