GuobaGuoba Utils

useUnmount

@guoba-ai/hook / useUnmount

Function: useUnmount()

function useUnmount(fn): void;

Defined in: useUnmount.ts:29

Run a callback when the component unmounts. The latest callback reference is always used, avoiding stale closure issues.

Parameters

fn

() => void

The callback to run on unmount

Returns

void

Example

useUnmount(() => {
  console.log('Component unmounted!')
})

function Subscription({ unsubscribe }: { unsubscribe: () => void }) {
  useUnmount(unsubscribe)
  return null
}

const { rerender, unmount } = renderHook(({ fn }) => useUnmount(fn), {
  initialProps: { fn: firstCleanup },
})
rerender({ fn: latestCleanup })
unmount()
// latestCleanup runs

Warning

The callback is not called on mount or re-render; it runs when the component unmounts.

On this page