Skip to content

useTitle

Category
Export Size
555 B
Last Changed
5 days ago

Reactive document title.

WARNING

This hook isn't compatible with SSR.

Demo

Usage

tsx
import { 
useTitle
} from '@reause/core'
const [
title
,
setTitle
] =
useTitle
()
console
.
log
(
title
) // print current title
setTitle
('Hello') // change current title

Set initial title immediately:

tsx
const [
title
] =
useTitle
('New Title')

Pass a value derived from state and the title will be updated when the source state changes:

tsx
import { 
useTitle
} from '@reause/core'
import {
useState
} from 'react'
const [
messages
,
setMessages
] =
useState
(0)
const
title
= !
messages
? 'No message' : `${
messages
} new messages`
useTitle
(
title
) // document title will match the state "title"

Pass an optional template tag Vue Meta Title Template to update the title to be injected into this template:

tsx
const [
title
] =
useTitle
('New Title', {
titleTemplate
: '%s | My Awesome Website'
})

WARNING

observe is incompatible with titleTemplate.

Type Declarations

ts
export interface UseTitleOptionsBase {
    document?: Document | null;
    restoreOnUnmount?: false | ((originalTitle: string, currentTitle: string) => string | null | undefined);
}

export type UseTitleOptions = UseTitleOptionsBase & ({
    observe?: boolean;
} | {
    titleTemplate?: string | ((title: string) => string);
})

export type UseTitleReturn = [
    title: string | null | undefined,
    setTitle: Dispatch<SetStateAction<string | null | undefined>>
]

export function useTitle(newTitle?: string | null | undefined, options?: UseTitleOptions): UseTitleReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
ab93e - fix(core): resolve useTitle audit findings (#673)

Released under the MIT License. v0.1.8