Skip to main content

All hooks

useDocumentTitle

Custom hook that sets the document title.


Setting preserveTitleOnUnmount to false allows the document title to be reset to its default value (defined by the <title> tag) when the component is unmounted.

Usage

import { useDocumentTitle } from './useDocumentTitle'

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

API

function useDocumentTitle(title: string, options?: UseDocumentTitleOptions): void

Custom hook that sets the document title.

Parameters

NameTypeDefault valueDescription
titlestring-The title to set.
options?UseDocumentTitleOptions{}The options.

Returns

No return description available yet.

Type declaration

UseDocumentTitleOptions

Hook options.

NameTypeDescription
preserveTitleOnUnmountbooleanWhether to keep the title after unmounting the component (default is true).

Hook

import { useRef } from 'react'

import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect'
import { useUnmount } from '../useUnmount'

/** Hook options. */
export type UseDocumentTitleOptions = {
  /** Whether to keep the title after unmounting the component (default is `true`). */
  preserveTitleOnUnmount?: boolean
}

/**
 * Custom hook that sets the document title.
 * @param {string} title - The title to set.
 * @param {?UseDocumentTitleOptions} [options] - The options.
 * @public
 * @see [Documentation](https://usehooks-ts.com/react-hook/use-document-title)
 * @example
 * ```tsx
 * useDocumentTitle('My new title');
 * ```
 */
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
    }
  })
}