JAVASCRIPT

Dynamically Updating Document Title with `useEffect`

Use the `useEffect` hook in React to programmatically change the browser's document title based on component state or props, enhancing user experience.

import React, { useState, useEffect } from 'react';

function DocumentTitleUpdater() {
  const [count, setCount] = useState(0);
  const [titleSuffix, setTitleSuffix] = useState('');

  // Effect to update the document title
  useEffect(() => {
    document.title = `Count: ${count}${titleSuffix ? ` | ${titleSuffix}` : ''}`;

    // Optional: Return a cleanup function if needed (not strictly necessary here)
    // return () => { document.title = 'React App'; };
  }, [count, titleSuffix]); // Dependencies array: re-run effect if count or titleSuffix changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>
        Increment Count
      </button>
      <p>Title Suffix:</p>
      <input
        type="text"
        value={titleSuffix}
        onChange={(e) => setTitleSuffix(e.target.value)}
        placeholder="Add to title..."
      />
    </div>
  );
}

// Example Usage:
// function App() {
//   return <DocumentTitleUpdater />;
// }
How it works: This snippet illustrates a straightforward use of the `useEffect` hook to manage side effects, specifically updating the browser's document title. The effect runs after every render where the values in its dependency array (`count` and `titleSuffix`) have changed. This allows for dynamic and reactive updates to the page's title based on component state, providing better context for the user without directly manipulating the DOM outside of React.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs