JAVASCRIPT
How to dynamically update the browser document title in React
Implement a custom `useDocumentTitle` React hook to easily manage and update the browser tab's title dynamically, enhancing user experience 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) {
document.title = defaultTitle.current;
}
}, []);
}
// Example Usage:
// function MyComponent() {
// useDocumentTitle('My Awesome Page');
// // ... rest of your component
// return <h1>Hello there!</h1>;
// }
// function AnotherComponent() {
// // This title will persist even if AnotherComponent unmounts
// useDocumentTitle('Persistent Page Title', true);
// return <p>This page has a title that sticks around.</p>;
// }
How it works: The `useDocumentTitle` hook allows you to set the browser's document title dynamically based on the component where it's used. It leverages `useEffect` to update `document.title` whenever the `title` prop changes. An optional `prevailOnUnmount` parameter dictates whether the title should revert to its original value when the component unmounts. This is particularly useful for single-page applications to provide context to users navigating different views.