UtilityBeginnerSSR-safehooks/utility/useUnmount.ts

useUnmount

Run a callback on unmount.

Import

TypeScript
import { useUnmount } from '@/hooks';

API

Signature

useUnmount(fn)

When to use

Use useUnmount instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Browser utilities are SSR-gated; lifecycle hooks are safe.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useUnmount
Editor
function TrackLeave() {
  useUnmount(() => console.log('bye'));
  return null;
}
Preview

Implementation source

Full library source for useUnmount — copy into your project when you are not installing a package yet.

hooks/utility/useUnmount.ts
import { useEffect } from 'react';
import { useLatest } from './useLatest';

/** Runs `fn` once when the component unmounts. */
export function useUnmount(fn: () => void): void {
  const fnRef = useLatest(fn);
  useEffect(
    () => () => {
      fnRef.current();
    },
    [fnRef],
  );
}

Copy-paste example

useUnmount.example.tsx
'use client';

import { useUnmount } from '@/hooks';

export function TrackLeave() {
  useUnmount(() => console.log('bye'));
  return null;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Lifecycle hooks are for side effects only — not for deriving render state.
  • Source of truth: open hooks/utility/useUnmount.ts for implementation details