useUnmount
Runs cleanup logic when the component unmounts.
Runs cleanup logic when the component unmounts.
Import
import { useUnmount } from '@kamod-ch/hooks'Live demo
Basic demo
Runs cleanup logic when the component unmounts.
Unmount count: 0
Hide this child to trigger cleanup.
import { useState } from 'preact/hooks'
import { useUnmount } from '@kamod-ch/hooks'
function Child({ onUnmount }: { onUnmount: () => void }) {
useUnmount(onUnmount)
return <p>Hide this child to trigger cleanup.</p>
}
export default function UseUnmountDemo() {
const [visible, setVisible] = useState(true)
const [unmounts, setUnmounts] = useState(0)
return (
<div>
<p><strong>Unmount count:</strong> {unmounts}</p>
<button type="button" onClick={() => setVisible((value) => !value)}>{visible ? 'Unmount child' : 'Mount child'}</button>
{visible ? <Child onUnmount={() => setUnmounts((value) => value + 1)} /> : null}
</div>
)
}
API
TypeScript signature
declare const useUnmount: (fn: () => void) => void;
export default useUnmount;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.