UtilityBeginnerSSR-safehooks/utility/useDidMount.ts

useDidMount

Run once after mount.

Import

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

API

Signature

useDidMount(fn)

When to use

Use useDidMount 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 · useDidMount
Editor
function Boot() {
  useDidMount(() => console.log('mounted'));
  return null;
}
Preview

Implementation source

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

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

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

Copy-paste example

useDidMount.example.tsx
'use client';

import { useDidMount } from '@/hooks';

export function Boot() {
  useDidMount(() => console.log('mounted'));
  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/useDidMount.ts for implementation details