Skip to content

Instantly share code, notes, and snippets.

@hunterwilhelm
Created October 20, 2022 18:12
Show Gist options
  • Save hunterwilhelm/dc466eba5417590afc507bb9b1dfc675 to your computer and use it in GitHub Desktop.
Save hunterwilhelm/dc466eba5417590afc507bb9b1dfc675 to your computer and use it in GitHub Desktop.
React Hook: Listen to the document title state & rerender when it changes
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;
}
@Hamza5
Copy link

Hamza5 commented Jun 15, 2025

Thank you for the implementation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment