Suppose we are reading an article online. The title of the article appears at the top of our browser tab. This is the document title, and it helps us understand what the page is about.
- In React , we can easily set the document title using few simple steps :
- Using the useEffect hook : This hook lets us run code after a component has been rendered.
- Set the title : Inside the useEffect hook , use document.title to set the new title.
For example:
import React , { useEffect } from 'react';
function My(){
useEffect(() => {
document.title = " Learner's Website ' ;
} , []);
return (
// ....your component's JSX
);
}
import React , { useEffect } from 'react';
function useDocumentTitle(title){
useEffect(() => {
document.title = title;
}, [title]);
}
function My(){
useDocumentTitle('Learner's Website');
return (
// ....your component's JSX
);
}
With this custom hook , you can simply pass the desired title as an argument, and the hook will take care of setting the document title for you.