useUnmount is a React hook that runs a cleanup function when the component unmounts.
Import
import { useUnmount } from '@legendapp/state/react';
Signature
function useUnmount(fn: () => void): void
Parameters
Function to run when the component unmounts
Returns
Void.
Examples
Basic usage
import { useUnmount } from '@legendapp/state/react';
function Component() {
useUnmount(() => {
console.log('Component unmounted');
});
return <div>Hello</div>;
}
Clean up subscriptions
function ChatRoom({ roomId }) {
useMount(() => {
const subscription = subscribeToChatRoom(roomId);
return subscription;
});
useUnmount(() => {
console.log(`Leaving chat room ${roomId}`);
// Additional cleanup
});
return <div>Chat Room</div>;
}
Save state on unmount
function Editor() {
const content$ = useObservable('');
useUnmount(() => {
// Save content to localStorage before unmounting
localStorage.setItem('draft', content$.get());
});
return (
<textarea
value={content$.get()}
onChange={(e) => content$.set(e.target.value)}
/>
);
}
Analytics tracking
function Page() {
const startTime = Date.now();
useUnmount(() => {
const timeSpent = Date.now() - startTime;
analytics.track('page_view_duration', { timeSpent });
});
return <div>Page content</div>;
}
Notes
- Runs only once when the component unmounts
- Internally uses
useMount to return the cleanup function
- The function cannot be async
- Useful for cleanup operations like logging, saving state, or closing connections