javascripthtmlreactjs

React - Resetting the document title when a user navigates away from the page


I am faced with a problem and I am hoping someone might know how to overcome it.

The pages across all of our site have a default title, as per our index.html file:

<html lang="en">
  <head>
    <title>My Page Title</title>
  </head>
  ...
</html>

This means that all tabs display the page title as per the index file.

On one page of the site, I want to override the title as per the information that is returned from a page load.

For example:

useEffect(() => {
  const displayTitle = loadTitle();
  document.title = displayTitle;
  }, []);

This works exactly as I would like, when the tab loads, the tab title is updated.

The issue however is when a user clicks a link to navigate away from that page. The tab title remains as the value that was loaded, despite another page having loaded within that tab. The tab title displays as that loaded value until the page is hard refreshed.

Is there any way for me to set the document title for a page via a load, like illustrated above, but to have it return to the default value once navigated away?


Solution

  • useEffect can be given a return value, which should take the form of a function that will be called when the component (or specifically the hook) unmounts.

    You can use this:

    useEffect(() => {
      const displayTitle = loadTitle();
      document.title = displayTitle;
    
      return () => document.title = ""; // However you'd like to reset the title
    }, []);
    

    See useEffect docs.