UtilityBeginnerSSR-safehooks/utility/useDocumentTitle.ts

useDocumentTitle

Set document.title.

Import

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

API

Signature

useDocumentTitle(title, options?)

When to use

Use useDocumentTitle 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 · useDocumentTitle
Editor
function Title({ name }: { name: string }) {
  useDocumentTitle(`${name} · Acme`);
  return null;
}
Preview

Implementation source

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

hooks/utility/useDocumentTitle.ts
import { useEffect } from 'react';
import { isBrowser } from './isBrowser';

export interface UseDocumentTitleOptions {
  /** Restore previous title on unmount. @default true */
  restoreOnUnmount?: boolean;
}

/** Sets `document.title` while mounted. */
export function useDocumentTitle(
  title: string,
  options: UseDocumentTitleOptions = {},
): void {
  const { restoreOnUnmount = true } = options;

  useEffect(() => {
    if (!isBrowser()) return;
    const previous = document.title;
    document.title = title;
    return () => {
      if (restoreOnUnmount) {
        document.title = previous;
      }
    };
  }, [title, restoreOnUnmount]);
}

Copy-paste example

useDocumentTitle.example.tsx
'use client';

import { useDocumentTitle } from '@/hooks';

export function Title({ name }: { name: string }) {
  useDocumentTitle(`${name} · Acme`);
  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/useDocumentTitle.ts for implementation details