'React: why set the document title inside useEffect?

I just watched a talk from React Conf 2018. In the video, the speaker shows 2 ways to set the document title. The first is by using the Lifecycle methods (componentDidMount and componentDidUpdate) if we use a class component, the second one is by using the useEffect hook if we use a function component. It looks like that's the recommended way to do it according to answers from this question.

But, I tested the following code and it seems to work just fine to set the document title directly:

import React from 'react';
import ReactDOM from 'react-dom';

function App() {
    document.title = 'wow'
    return <p>Hello</p>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)

The title changed:
screenshot

Is there any significance of setting the document title inside useEffect or componentDidMount?
Or is it because it was the only way to set the document title?
Is it okay to set the document title directly like I did in the snippet above?

Update:

It also works with class component:

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    render() {
        document.title = 'wow'
        return <p>Hello</p>
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)


Solution 1:[1]

Use react-helment which is also widely used in other frameworks with the same name as helmet express ...

Here is the same code:

import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
                <link rel="canonical" href="http://example.org/example" />
            </Helmet>
            ...
        </div>
    );
  }
};

Another way to use via props to which is cleaner IMO

...
<Helmet titleTemplate={`%s | ${props.title}`} defaultTitle={constants.defaultTitle} />

You may also use react-helmet-async for more features.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lalit Yadav