Skip to content

useDocumentTitle

Custom hook that sets the document title.

Usage

tsx
import { useDocumentTitle } from 'vhooks'

export default function Component() {
  useDocumentTitle('foo bar')
}

Installation

sh
pnpm dlx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useDocumentTitle.json -e %src%/hooks
sh
npx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useDocumentTitle.json -e %src%/hooks
sh
bunx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useDocumentTitle.json -e %src%/hooks
sh
yarn dlx scaflo@latest https://raw.githubusercontent.com/programming-with-ia/vDocs/scaflos/hooks/useDocumentTitle.json -e %src%/hooks

API

useDocumentTitle(title, options?): void

Custom hook that sets the document title.

Parameters

NameTypeDescription
titlestringThe title to set.
options?UseDocumentTitleOptionsThe options.

Returns

void

Type aliases

Ƭ UseDocumentTitleOptions: Object

Hook options.

Type declaration

NameTypeDescription
preserveTitleOnUnmount?booleanWhether to keep the title after unmounting the component (default is true).

Hook

ts
import { useRef } from 'react'

import { useIsomorphicLayoutEffect, useUnmount } from 'vhooks'

type UseDocumentTitleOptions = {
    preserveTitleOnUnmount?: boolean
}

export function useDocumentTitle(
  title: string,
  options: UseDocumentTitleOptions = {},
): void {
  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) {
      window.document.title = defaultTitle.current
    }
  })
}

vDocs