useTitle

React hook to change the page title.

Add the hook via the CLI:

npx @novajslabs/cli add useTitle

Or copy and paste the code into your project:

import { useState, useEffect } from 'react'

interface UseTitleOutput {
  title: string
  changeTitle: (newTitle: string) => void
}

export const useTitle = (): UseTitleOutput => {
  const [title, setTitle] = useState<string>(document.title)

  useEffect(() => {
    document.title = title
  }, [title])

  const changeTitle = (newTitle: string) => setTitle(newTitle)

  return { title, changeTitle }
}

React 16.8 or higher

  • Name
    title
    Type
    string
    Description

    The current value of the page title.

  • Name
    changeTitle
    Type
    function
    Description

    Set the page title. This function accepts the new title.

import { useTitle } from './hooks/useTitle'

const App = () => {
  const { title, changeTitle } = useTitle()

  const toggleTitle = () => {
    if (title === 'Title 1') {
      changeTitle('Title 2')
    } else {
      changeTitle('Title 1')
    }
  }

  return <button onClick={toggleTitle}>Toggle title</button>
}

export default App

Here are some use cases where this React hook is useful:

  • Dynamically updating the title of a web page based on user interactions in a single-page application
  • Changing the title of a web-based presentation or slideshow as the slides progress
  • Personalizing the page title for individual users based on their profile or preferences in a web application