-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add option to useTitle to restore title on un-mount
- Loading branch information
Showing
2 changed files
with
31 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,22 @@ | ||
import { useRef } from 'react'; | ||
|
||
function useTitle(title: string) { | ||
const t = useRef<string>(); | ||
|
||
if (t.current !== title) { | ||
document.title = t.current = title; | ||
} | ||
import { useRef, useEffect } from 'react'; | ||
export interface UseTitleOptions { | ||
restoreOnUnmount?: boolean; | ||
} | ||
const DEFAULT_USE_TITLE_OPTIONS: UseTitleOptions = { | ||
restoreOnUnmount: false, | ||
}; | ||
function useTitle(title: string, options: UseTitleOptions = DEFAULT_USE_TITLE_OPTIONS) { | ||
const prevTitleRef = useRef(document.title); | ||
document.title = title; | ||
useEffect(() => { | ||
if (options && options.restoreOnUnmount) { | ||
return () => { | ||
document.title = prevTitleRef.current; | ||
}; | ||
} else { | ||
return; | ||
} | ||
}, []); | ||
} | ||
|
||
export default typeof document !== 'undefined' ? useTitle : (_title: string) => {}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters