JAVASCRIPT
Dynamically Update Browser Document Title
Learn to build `useDocumentTitle`, a custom React hook for declaratively setting the browser tab's title, useful for dynamic page titles in single-page applications.
import { useEffect, useRef } from 'react';
function useDocumentTitle(title, prevailOnUnmount = false) {
const defaultTitle = useRef(document.title);
useEffect(() => {
document.title = title;
}, [title]);
useEffect(() => {
if (!prevailOnUnmount) {
return () => {
document.title = defaultTitle.current;
};
}
}, [prevailOnUnmount]);
}
export default useDocumentTitle;
// Example Usage:
// function ProductPage({ productName }) {
// useDocumentTitle(`${productName} - My Store`, false); // Resets on unmount
//
// return (
// <div>
// <h1>{productName}</h1>
// <p>This is the product description.</p>
// </div>
// );
// }
//
// function HomePage() {
// useDocumentTitle('Welcome to My Store', true); // Persists on unmount
//
// return (
// <div>
// <h1>Welcome!</h1>
// <p>Explore our latest products.</p>
// </div>
// );
// }
How it works: The `useDocumentTitle` hook allows you to easily set the title of the browser tab from within a React component. It takes a `title` string and an optional `prevailOnUnmount` boolean. When the component mounts or the `title` changes, the document title is updated. If `prevailOnUnmount` is false, the title will revert to its original value when the component unmounts, ensuring clean state management across different routes or views.