Skip to main content
Version: 0.2.0

useDocumentTitle

Sets document.title declaratively and restores the original title on unmount (unless opted out).

Signature

function useDocumentTitle(title: string, persistOnUnmount?: boolean): void

Parameters

ParameterTypeDefaultDescription
titlestringThe title to set
persistOnUnmountbooleanfalseWhen true, the title is not restored when the component unmounts

Behaviour

  • Sets document.title immediately on each render when title changes.
  • Captures the original title in a ref on mount.
  • Restores the original title on unmount, unless persistOnUnmount is true.

Example

import { useDocumentTitle } from "@julianfere/hooked";

function ProductPage({ name }: { name: string }) {
useDocumentTitle(`${name} — My Shop`);
return <h1>{name}</h1>;
}
note

This hook interacts with document.title which is not available in server-side rendering environments. In an SSR setup, ensure the hook only runs on the client.