useUnmountedRef
Mutable ref that flips to true after unmount.
Mutable ref that flips to true after unmount.
Import
import { useUnmountedRef } from '@kamod-ch/hooks'Live demo
Basic demo
Mutable ref that flips to true after unmount.
Unmounted flag: false
import { useState } from 'preact/hooks'
import { useUnmountedRef } from '@kamod-ch/hooks'
function Child() {
const ref = useUnmountedRef()
return <p><strong>Unmounted flag:</strong> {String(ref.current)}</p>
}
export default function UseUnmountedRefDemo() {
const [visible, setVisible] = useState(true)
return (
<div>
<button type="button" onClick={() => setVisible((value) => !value)}>{visible ? 'Unmount child' : 'Mount child'}</button>
{visible ? <Child /> : <p>After unmount the ref inside the child becomes true.</p>}
</div>
)
}
API
TypeScript signature
declare const useUnmountedRef: () => import("preact/hooks").MutableRef<boolean>;
export default useUnmountedRef;
/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.