useDocumentTitle
A React hook for dynamically managing the document title of your page. Automatically updates the browser tab title and optionally restores it when the component unmounts.
- Installation
- Add Source Code
npm install @plenty-hooks/use-document-title
npx @plenty-hooks/cli use-document-title
Using this command will add the source code of the hook directly to your project.
Options:
--pathor-p: Specify the directory where the hook file should be saved--kebab-caseor-k: Use kebab-case for the output filename (e.g.,use-document-title.ts). By default, the filename uses camelCase (e.g.,useDocumentTitle.ts)
Note: By adding the source code of the hook directly to your project, you won't be able to install further updates automatically. You are on your own for maintaining and updating the code.
Showcase
import { useDocumentTitle } from '@plenty-hooks/use-document-title';
function DashboardPage() {
const setTitle = useDocumentTitle('Dashboard - My App');
const handleNotification = () => {
// Manually update the title when needed
setTitle('(1) Dashboard - My App');
};
return (
<div>
<h1>Dashboard</h1>
<button onClick={handleNotification}>
Simulate Notification
</button>
</div>
);
}
Keeping Title on Unmount
By default, the title is reset when the component unmounts. You can preserve it using the keepOnUnmount option:
import { useDocumentTitle } from '@plenty-hooks/use-document-title';
function PersistentTitleComponent() {
useDocumentTitle('My Persistent Title', { keepOnUnmount: true });
return <div>This title will remain even after unmounting</div>;
}
Global Configuration
Configure default options globally for all instances:
import { configUseDocumentTitle } from '@plenty-hooks/use-document-title';
// Configure once in your app entry point
configUseDocumentTitle({
keepOnUnmount: true
});
API
useDocumentTitle(title: string, options?: Options)
Sets the document title and returns a function to manually update it.
Parameters
title: string- The title to set for the documentoptions(optional): Configuration object with the following properties:keepOnUnmount?: boolean- If true, the document title will not be reset on unmount (default:false)
Returns
setDocumentTitle: (newTitle: string) => void- A function to manually update the document title
configUseDocumentTitle(options: Options)
Configures global default options for all useDocumentTitle instances.
Parameters
options: Configuration object with the following properties:keepOnUnmount?: boolean- If true, the document title will not be reset on unmount (default:false)
Types
interface Options {
keepOnUnmount?: boolean;
}