Effects
useDocumentTitle
Keeps document.title in sync with a value, SSR-safe.
Demo
live · imported from hookli
- 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.
import { useDocumentTitle } from "hookli";
export function Demo() {
useDocumentTitle("Dashboard — hookli", {
preserveTitleOnUnmount: false,
});
return <h1>Dashboard</h1>;
}Usage
import { useDocumentTitle } from "hookli";
export function Demo() {
useDocumentTitle("Dashboard — hookli", {
preserveTitleOnUnmount: false,
});
return <h1>Dashboard</h1>;
}API
useDocumentTitle(title: string, options?: UseDocumentTitleOptions): voidParameters
| Name | Type | Default | Description |
|---|---|---|---|
| title | string | — | The document title to apply. Written to document.title in a layout effect on the client and skipped during server rendering. |
| options | UseDocumentTitleOptions | {} | Behaviour options (see below). |
Returns
This hook returns nothing.
UseDocumentTitleOptions
Options controlling unmount behaviour.
| Name | Type | Description |
|---|---|---|
| preserveTitleOnUnmount | boolean | When 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.
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;
}
});
};