useDocumentTitleLoading saved progress…

useDocumentTitle

The browser tab's label is document.title, and single-page apps have to manage it by hand — there's no <title> re-render on navigation the way a server-rendered page gets. useDocumentTitle is the small hook that owns it: point a component at a title string and it keeps the tab in sync, then puts the old title back when the component leaves. Think "unread count in the tab" or a route that shows the current page name.

Implement useDocumentTitle(title). While the component is mounted, document.title should equal title (re-applying whenever title changes). When the component unmounts, restore whatever the title was before the hook first ran.

Signature

function useDocumentTitle(title) {
  // side-effect only; returns nothing.
}

Examples

function InboxPage({ unread }) {
  useDocumentTitle(unread ? `(${unread}) Inbox` : 'Inbox');
  // tab reads "(3) Inbox"; navigating away restores the prior title
}
useDocumentTitle('Checkout');   // tab is "Checkout"
// ...component unmounts -> tab goes back to whatever it said before

Notes

  • Sync on change — apply the title in an effect keyed on title, so a new title argument re-applies.
  • Capture the previous title once — record document.title on the first run (a ref set on mount), not on every change. Otherwise unmount restores an intermediate title instead of the original.
  • Restore on unmount — the effect's cleanup should put the captured previous title back.
  • No return value — this is a pure side-effect hook.
Loading editor…