Created
October 20, 2022 18:12
-
-
Save hunterwilhelm/dc466eba5417590afc507bb9b1dfc675 to your computer and use it in GitHub Desktop.
React Hook: Listen to the document title state & rerender when it changes
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
import { useEffect, useState } from "react"; | |
export function useReadDocumentTitle() { | |
const [title, setTitle] = useState(document.title); | |
useEffect(() => { | |
const titleElem = document.querySelector('title'); | |
if (!titleElem) return; | |
const observer = new MutationObserver(function (mutations) { | |
setTitle(mutations[0].target.textContent ?? ''); | |
}); | |
observer.observe( | |
titleElem, | |
{ subtree: true, characterData: true, childList: true } | |
); | |
return () => { | |
observer.disconnect(); | |
} | |
}, []) | |
return title; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment