Effects

useDocumentTitle

Keeps document.title in sync with a value, SSR-safe.

Demo

document.title
Look up at the tab ✦

Type above and the browser tab updates as you go. Restoring unmounts the hook, which puts back the title it captured on mount.

Usage

use-document-title.tsxtsx
import { useDocumentTitle } from "hookli";

export function Demo() {
  useDocumentTitle("Dashboard — hookli", {
    preserveTitleOnUnmount: false,
  });

  return <h1>Dashboard</h1>;
}

API

useDocumentTitle.d.tsts
useDocumentTitle(title: string, options?: UseDocumentTitleOptions): void

Parameters

NameTypeDefaultDescription
titlestringThe document title to apply. Written to document.title in a layout effect on the client and skipped during server rendering.
optionsUseDocumentTitleOptions{}Behaviour options (see below).

Returns

This hook returns nothing.

UseDocumentTitleOptions

Options controlling unmount behaviour.

NameTypeDescription
preserveTitleOnUnmountbooleanWhen false, the title captured on mount is restored when the component unmounts. Defaults to true, which leaves the title in place.

Hook

The implementation, straight from hookli. Copy it, or install the package.

src/hooks/use-document-title/use-document-title.tstsx
import { useRef } from "react";
import { useIsomorphicLayoutEffect } from "../use-isomorphic-layout-effect/use-isomorphic-layout-effect";
import { useUnmount } from "../use-unmount/use-unmount";

interface UseDocumentTitleOptions {
  preserveTitleOnUnmount?: boolean;
}

export const useDocumentTitle = (
  title: string,
  options: UseDocumentTitleOptions = {},
) => {
  const { preserveTitleOnUnmount = true } = options;
  const defaultTitle = useRef<string | null>(null);

  useIsomorphicLayoutEffect(() => {
    defaultTitle.current = window.document.title;
  }, []);

  useIsomorphicLayoutEffect(() => {
    window.document.title = title;
  }, [title]);

  useUnmount(() => {
    if (!preserveTitleOnUnmount && defaultTitle.current !== null) {
      window.document.title = defaultTitle.current;
    }
  });
};

View source on GitHub

Related hooks