reactjspage-title

How to change a page's title when loading it in React without delay?


I started learning React from Angular and I'm having trouble changing the pages'title dynamically, and I don't know if there is a better way of doing it than what I'm doing right now. I have, on each page, the following hook:

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

But with this hook I find a problem: there is a little delay (of a little less than a second) when navigating to another page. Is there another way of doing this? (I've tried react-helmet but it still has that little delay)


Solution

  • if you need to change the page title synchronously (i.e., before the browser has painted the screen), you should use the useLayoutEffect hook. Here's an example:

    import React, { useLayoutEffect } from 'react';
    
    function MyComponent() {
      useLayoutEffect(() => {
       document.title = 'New Page Title';
      }, []);
    
     return (
      // your component code here
     );
    }