useIsMounted
Check if a component is currently mounted.
Installation
Copy-paste the hook
Copy and paste the hook code in a .ts
file.
Usage
Details
State management
- Uses
useRef
to mantain a mutable reference (isMounted.current
) that persist for the full lifetime of the component. - The value of
isMounted.current
is update dyrectly in theuseEffect
hook.
Re-rendering behavior
- The hook does not cause re-renders when the mounted state changes because it uses
useRef
. The value can be accessed without triggering a re-render. - This can be beneficial for performance, especially in scenarios where the mounted state is checked frequently.
Return value
- Returns an object with a memoized callback function that returns the current value of
isMounted.current
. This allows for a consistent reference to the mounted state without causing re-renders.