Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating document title without hooks

Is it required to use a hook for updating document.title? Is there any advantage to using useEffect vs. just setting the title directly as below?

(This snippet also echoes the title to the console, since you can't see the document title in Stack Snippets, but in my real code I'm just updating the title.)

const { useState } = React;

function Example() {
  const [count, setCount] = useState(0);

  document.title = `You clicked ${count} times`;
  console.log(document.title);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('app'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="app"></div>

(Note: This is the useEffect example without the useEffect call.)

like image 861
A dev Avatar asked Apr 22 '19 09:04

A dev


People also ask

Which hook can be used to update the document title?

Q . Which Hook could be used to update the document's title? useEffect(function updateTitle() { document.

How do I change my title in Reactjs?

Changing the title tag​ You can find the source HTML file in the public folder of the generated project. You may edit the <title> tag in it to change the title from “React App” to anything else.

How do I change the title of each page in react?

import { Helmet } from 'react-helmet'; When we go to the Guides page in the browser, we get our customized title in the tab: “CoderGuides | Guides.” That's all there is to it. So, to customize the title for all your pages, just repeat the same steps for each page you want to customize the title for.

How do I add a document title in react?

Setting document title in class components In class components, we can use the componentDidMount() lifecycle method to set a document title. import React from "react"; class App extends React. Component { componentDidMount() { document.


1 Answers

It may cause inconsistency in the future.

After concurrent mode, render may be abandoned when high priority task comes before react lifecycle.

Then at that moment document.title is not equal to the value in dom.

In your case, maybe title is You clicked 2 times but dom You clicked 1 times.

It is not what react is doing now(react@16). But it will happen.

like image 160
dancerphil Avatar answered Oct 16 '22 05:10

dancerphil