h3/use's logo

h3/use

Command Palette

Search for a command to run...

usePageTitle

Hook to modify the page title dynamically

Page Title Demo
Change the page title dynamically
Current document title: Not available on server

Installation

Props

PropTypeDefaultDescription
optionsPageTitleOptionsundefinedOptional configurations for title

Options

PropTypeDefaultDescription
suffixstring""Suffix to be added to the title
separatorstring" - "Separator between the title and suffix

Data

The hook returns an object with the following properties:

PropertyTypeDescription
setTitle(title: string) => voidSets the page title
resetTitle() => voidRestores the original page title

Key Features & Details

  • Modifies the page title (document.title) dynamically
  • Support for adding suffix to the title (e.g., "Page - My Site")
  • Automatically restores the original title when the component is unmounted
  • Safe for SSR (Server-Side Rendering)

Browser Support

This hook works in all modern browsers that support JavaScript:

  • Chrome: Supported
  • Firefox: Supported
  • Safari: Supported
  • Edge: Supported
  • Opera: Supported

Performance Considerations

  • The hook uses useCallback to avoid unnecessary renders
  • The effect cleanup ensures the title is restored when the component is unmounted
  • Existence checks for the document object for SSR compatibility

Best Practices & Caveats

  1. Always use the hook within client-side components
  2. For Next.js applications, also consider using the <Head> component for SEO
  3. Prefer short and descriptive titles for better user experience
  4. Use the suffix to include the site or application name
  5. Make sure to call resetTitle if you want to manually restore the title

Examples

Basic Usage

import { usePageTitle } from '@/hooks/use-page-title';
 
function MyComponent() {
  const { setTitle } = usePageTitle();
 
  return (
    <button onClick={() => setTitle('New Page Title')}>Change Title</button>
  );
}

With Suffix

import { usePageTitle } from '@/hooks/use-page-title';
 
function MyComponent() {
  const { setTitle } = usePageTitle({
    suffix: 'My Website',
    separator: ' - ',
  });
 
  // Will set the title to "Dashboard - My Website"
  return <button onClick={() => setTitle('Dashboard')}>Go to Dashboard</button>;
}

With Reset Functionality

import { usePageTitle } from '@/hooks/use-page-title';
 
function MyComponent() {
  const { setTitle, resetTitle } = usePageTitle();
 
  return (
    <div>
      <button onClick={() => setTitle('New Title')}>Change Title</button>
      <button onClick={resetTitle}>Reset Title</button>
    </div>
  );
}