Skip to content

Dynamic Document Titles in Next.js 15

Published: at 03:00 AM

While dynamic document titles using the <title> tag directly in JSX is a React feature (see React documentation), let’s explore how to implement it effectively in a Next.js 15 application.

How It Works

React allows you to include a <title> tag directly in your JSX, and Next.js 15 fully supports this React feature out of the box. When your component renders or re-renders, React automatically updates the document title to match the content of your <title> tag.

Why It Works

This feature leverages React’s built-in capabilities for managing document metadata, combined with Next.js 15’s server-side rendering and client-side hydration. When state changes occur, React efficiently updates the document title without requiring additional API calls or manual DOM manipulation.

Example: Counter with Dynamic Title in Next.js 15

Here’s an example of implementing a counter with dynamic title in a Next.js 15 application:

'use client'

import { useState } from 'react'

export default function CounterWithDynamicTitle() {
  const [count, setCount] = useState(0)

  const incrementCount = () => {
    setCount(prevCount => prevCount + 1)
  }

  return (
    <>
      <title>Count: {count}</title>
      <div>
        <h1>Counter: {count}</h1>
        <button onClick={incrementCount}>Increment</button>
      </div>
    </>
  )
}

In this Next.js 15 example:

  1. We use the ‘use client’ directive since we’re using state
  2. The <title> tag is included directly in the JSX, using the current count value
  3. When the “Increment” button is clicked, it updates the count state
  4. As the component re-renders, both the displayed count and the document title are updated

This approach simplifies the process of managing dynamic document titles, making it more intuitive and reducing the need for side effects or additional hooks.

Key Benefits in Next.js 15

This React feature, when used in Next.js 15, provides a clean and efficient way to manage dynamic document titles in your application, particularly beneficial when building dynamic, server-rendered React applications.

Inspiration for this post


Previous Post
AI SDK by Vercel vs. Pydantic AI
Next Post
AI SDK by Vercel: A 30,000 Feet View