useDocumentTitle Hook
A custom React Hook to manage document title with TypeScript support
Code
import { useEffect, useRef } from 'react';
function useDocumentTitle(title: string, restoreOnUnmount = true): void {
const originalTitle = useRef<string | null>(null);
useEffect(() => {
// Save original title on first mount
__TOKEN_14__ (originalTitle.current === null) {
originalTitle.current = document.title;
}
// Update title
document.title = title;
// Restore original title on unmount if needed
__TOKEN_15__ () => {
__TOKEN_16__ (restoreOnUnmount && originalTitle.current) {
document.title = originalTitle.current;
}
};
}, [title, restoreOnUnmount]);
}
// Usage example
// useDocumentTitle('Home | My App');
// // Restore original title when component unmounts
// useDocumentTitle('Profile | My App', true);
// // Keep new title after unmount
// useDocumentTitle('Error 404 | My App', false);