JAVASCRIPT
Synchronizing Document Title with Component State using useEffect
Dynamically update the browser's document title based on your React component's state or props using the useEffect hook, improving user experience and SEO. Includes cleanup.
import React, { useState, useEffect } from 'react';
function PageTitleUpdater({ pageName }) {
const [visitCount, setVisitCount] = useState(0);
useEffect(() => {
// Set a new document title
document.title = `Page: ${pageName} | Visits: ${visitCount}`;
// Optional cleanup function (e.g., if you were adding/removing event listeners)
// For document.title, cleanup is often not necessary unless you need to revert it.
return () => {
// document.title = 'Default App Title'; // Example cleanup if needed
};
}, [pageName, visitCount]); // Re-run effect when pageName or visitCount changes
return (
<div>
<h1>Welcome to {pageName}!</h1>
<p>You've visited this page {visitCount} times.</p>
<button onClick={() => setVisitCount(prev => prev + 1)}>Increment Visit Count</button>
</div>
);
}
export default PageTitleUpdater;
How it works: The `useEffect` hook is used here to perform side effects that interact with the browser's API, specifically updating the document's title. The effect runs after every render where the dependencies (`pageName`, `visitCount`) have changed. This keeps the browser tab's title synchronized with the component's internal state. The optional return function within `useEffect` would be used for cleanup, like removing event listeners or resetting the title to a default, though for simple title updates, it's often omitted.