How to Add a Dynamic Page Title in React Without Package
In this lesson, we are going to see how to add a dynamic page title in react js, we will use a custom hook to do that without using any packages.
Create a custom hook
First, let's create a custom hook that we will use to update the page title dynamically the file name is "useTitle".
import { useEffect } from 'react';
export default function useTitle(title) {
useEffect(() => {
document.title = `React Shopping Cart - ${title}`
}, [title]);
return null;
}
Update the page title dynamically
Now inside your components, you can use the custom hook to change the page title dynamically.
import React from 'react';
import useTitle from './useTitle';
export default function Home() {
useTitle('Home');
return (
<>
Home Page
</>
);
}