The current theme ("light" or "dark")
function MyApp() {
const theme = useDocumentTheme();
return <div>{theme === "dark" ? <DarkIcon /> : <LightIcon />}</div>;
}
function ThemedButton() {
const theme = useDocumentTheme();
return (
<button
style={{
background: theme === "dark" ? "#333" : "#fff",
color: theme === "dark" ? "#fff" : "#333",
}}
>
Click me
</button>
);
}
getDocumentTheme for the underlying functionapplyDocumentTheme to set the theme
React hook that provides the current document theme reactively.
Uses a
MutationObserverto watch for changes to thedata-themeattribute orclassondocument.documentElement. When the theme changes (e.g., from host context updates), the hook automatically re-renders your component with the new theme value.The
MutationObserveris automatically disconnected when the component unmounts.