useTitle
Hook to handling app page title. It works outside Component also and it returns array of two functions to read and write title.
Demo
INFO
First, in a variable outside the component is kept track of the page title. The useTitle hook is invoked in the component with the title Title 1 parameter and the returned setTitle function is used. After 3 seconds the title is changed with the setTitle function to title Title 2.
When the component is unmounted, the title saved in the variable outside the component is set as the title.
Loading demo…
Show source code
tsx
import { useEffect } from "react";
import { useTitle } from "../../../.."
const previousTitle = useTitle()[0]();
export const UseTitle = () => {
const [,setTitle] = useTitle("Title 1");
useEffect(() => {
const id = setTimeout(() => {
setTitle("Title 2");
}, 3000);
return () => {
clearTimeout(id);
setTitle(previousTitle);
}
}, [setTitle]);
}Types
UseTitleProps
Parameters accepted by useTitle.
| Property | Type | Required | Description |
|---|---|---|---|
title | string | Optional title to set on document.title immediately. When provided, the title is applied both synchronously in the render body (for non-React environments such as SSR or usage outside a component tree) and inside a useLayoutEffect for standard React usage. When omitted, the current document title is left unchanged. |
UseTitleResult
Return value of useTitle.
| Index | Type | Description |
|---|---|---|
[0] | () => string | Returns the current value of document.title at call time. Not reactive — does not trigger a re-render when the title changes externally. Call it on demand when you need to read the latest title. |
[1] | (title: string) => void | Sets document.title to the provided string immediately. Can be called at any time, inside or outside a component, and takes effect synchronously. |
