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:
- We use the ‘use client’ directive since we’re using state
- The
<title>
tag is included directly in the JSX, using the currentcount
value - When the “Increment” button is clicked, it updates the
count
state - 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
- Server-Side Rendering: Works seamlessly with Next.js’s SSR capabilities
- Simplicity: No need for separate useEffect hooks or external libraries
- Reactivity: The title updates automatically with state changes
- App Router Compatible: Works perfectly with Next.js 15’s app router
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
React's <title> in Next.js 15 pic.twitter.com/wI39BOTM1a
— Alex Sidorenko (@asidorenko_) January 24, 2025