A React hook that executes a callback when the component unmounts
npm install @usefy/use-unmountA React hook that executes a callback when the component unmounts.
- Closure Freshness: Callback always has access to the latest state/props values
- Error Handling: Errors in callback are caught and don't break unmount
- Conditional Execution: Enable/disable cleanup via enabled option
- SSR Compatible: Works safely with server-side rendering
- TypeScript Support: Full type definitions included
- Zero Dependencies: Only peer dependency on React
``bash`
npm install @usefy/use-unmountor
pnpm add @usefy/use-unmountor
yarn add @usefy/use-unmount
`tsx
import { useUnmount } from "@usefy/use-unmount";
function MyComponent() {
useUnmount(() => {
console.log("Component unmounted");
});
return
$3
`tsx
import { useState } from "react";
import { useUnmount } from "@usefy/use-unmount";function FormComponent() {
const [formData, setFormData] = useState({});
useUnmount(() => {
// formData will have the latest value at unmount time
saveToLocalStorage(formData);
});
return
;
}
`$3
`tsx
import { useUnmount } from "@usefy/use-unmount";function TrackingComponent({ trackingEnabled }) {
useUnmount(
() => {
sendAnalyticsEvent("component_unmounted");
},
{ enabled: trackingEnabled }
);
return
Tracked content;
}
`$3
`tsx
import { useEffect, useRef } from "react";
import { useUnmount } from "@usefy/use-unmount";function WebSocketComponent() {
const wsRef = useRef(null);
useEffect(() => {
wsRef.current = new WebSocket("wss://example.com");
}, []);
useUnmount(() => {
wsRef.current?.close();
});
return
Connected;
}
`API
$3
#### Parameters
| Name | Type | Description |
| ---------- | ------------------- | ------------------------------------------- |
|
callback | () => void | Function to execute when component unmounts |
| options | UseUnmountOptions | Optional configuration |#### Options
| Name | Type | Default | Description |
| --------- | --------- | ------- | -------------------------------------- |
|
enabled | boolean | true | Whether to execute callback on unmount |React StrictMode
In development with React StrictMode, components are intentionally mounted, unmounted, and remounted to detect side effects. This means the unmount callback may be called multiple times during development. This is expected behavior.
Error Handling
If the callback throws an error, it will be caught and logged to the console. This prevents unmount errors from breaking the entire component tree unmount process.
When to Use
Use
useUnmount when you need to:- Save data before component removal
- Send analytics events on component exit
- Clean up resources that aren't managed by useEffect
- Log component lifecycle events
- Perform final state snapshots
When NOT to Use
Consider using
useEffect cleanup instead when:- Cleaning up subscriptions (use
useEffect return function)
- Removing event listeners (use useEventListener hook)
- Canceling requests (use abort controllers in useEffect)The key difference is that
useUnmount guarantees access to the latest values, while useEffect` cleanup captures values at effect creation time.This package maintains comprehensive test coverage to ensure reliability and stability.
📊 View Detailed Coverage Report (GitHub Pages)
Basic Functionality Tests
- Callback execution on unmount
- No callback execution on mount
- No callback execution on rerender
Closure Freshness Tests
- Callback accesses latest values at unmount time
- Updated callback reference is used on unmount
- Latest state values are captured in callback
Enabled Option Tests
- Default enabled state (true)
- Explicit enabled: true
- Disabled when enabled: false
- Dynamic enabled state changes
- Multiple enabled toggles
Error Handling Tests
- Errors in callback are caught and logged
- Unmount process continues despite callback errors
- Non-Error objects thrown are handled
Multiple Instances Tests
- Independent instances work correctly
- Multiple hooks in same component
- Independent enabled states per instance
Edge Cases Tests
- Rapid mount/unmount cycles
- Undefined options handling
- Empty options object
- Null-ish enabled values
Callback Reference Stability Tests
- Effect doesn't re-run when callback reference changes
Async Callback Tests
- Async callbacks are executed on unmount
- Async error handling behavior
---
MIT © mirunamu
This package is part of the usefy monorepo.
---
Built with care by the usefy team