useTitle
React hook to change the page title.
Add the hook via the CLI:
sh
npx @novajslabs/cli add useTitle
sh
npx @novajslabs/cli add useTitle
sh
pnpm dlx @novajslabs/cli add useTitle
Or copy and paste the code into your project:
ts
import { useState, useEffect } from "react";
interface UseTitleOutput {
title: string;
changeTitle: (newTitle: string) => void;
}
export const useTitle = (): UseTitleOutput => {
const [title, setTitle] = useState<string>(document.title);
useEffect(() => {
document.title = title;
}, [title]);
const changeTitle = (newTitle: string) => setTitle(newTitle);
return { title, changeTitle };
};
js
import { useState, useEffect } from "react";
export const useTitle = () => {
const [title, setTitle] = useState(document.title);
useEffect(() => {
document.title = title;
}, [title]);
const changeTitle = (newTitle) => setTitle(newTitle);
return { title, changeTitle };
};
Requirements
React 16.8 or higher
Return values
title
Type: string
The current value of the page title.
changeTitle
Type: function
Set the page title. This function accepts the new title.
Example
tsx
import { useTitle } from "./hooks/useTitle";
const App = () => {
const { title, changeTitle } = useTitle();
const toggleTitle = () => {
if (title === "Title 1") {
changeTitle("Title 2");
} else {
changeTitle("Title 1");
}
};
return <button onClick={toggleTitle}>Toggle title</button>;
};
export default App;
Use cases
Here are some use cases where this React hook is useful:
- Dynamically updating the title of a web page based on user interactions in a single-page application
- Changing the title of a web-based presentation or slideshow as the slides progress
- Personalizing the page title for individual users based on their profile or preferences in a web application