useDocumentTitle
A custom hook that dynamically changes document.title, independent of SEO.
If the preserveTitleOnUnmount option is set to true, the changed title will be preserved on unmount.
Code
Interface
typescript
interface UseDocumentTitleOption {
preserveTitleOnUnmount?: boolean; // default: false
}
const useDocumentTitle: (
title: string,
{ preserveTitleOnUnmount }?: UseDocumentTitleOption
) => void;
Options
| Name | Type | Default | Description |
|---|---|---|---|
preserveTitleOnUnmount | boolean | false | If true, the changed title is preserved when the component unmounts instead of reverting to the previous title |
Usage
typescript
import { useState } from 'react';
import { useDocumentTitle } from '@modern-kit/react';
const Example = () => {
const [title, setTitle] = useState('useDocumentTitle');
const [inputValue, setInputValue] = useState('');
const handleChangeTitle = () => {
setTitle(inputValue);
alert('Title has been changed.');
};
useDocumentTitle(title, {
preserveTitleOnUnmount: false, // default: false
});
return (
<div>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button onClick={handleChangeTitle}>Change Title</button>
</div>
);
};