All files / hooks useThemeMode.ts

100% Statements 15/15
100% Branches 5/5
100% Functions 1/1
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 301x 1x                       1x 2x 2x 2x   2x   2x 2x 2x   2x 1x 1x 2x 2x  
import { useEffect } from "react";
import { useStores } from "./useStores";
 
/**
 * A custom React hook that synchronizes the application's theme mode with the
 * document's data-theme attribute. It listens to changes in the theme mode
 * from the theme mode store and applies the appropriate theme (light or dark)
 * to the document element.
 *
 * The hook sets the `data-theme` attribute on the document based on the
 * `isLight` state from the theme mode store `useThemeModeStore`. It removes the attribute when
 * the component using this hook unmounts.
 */
export const useThemeMode = () => {
	const HTML_ATTRIBUTE = "data-theme";
	const LIGHT_VALUE = "light";
	const DARK_VALUE = "dark";
 
	const { theme } = useStores();
 
	useEffect(() => {
		const mode = theme.isLight ? LIGHT_VALUE : DARK_VALUE;
		document.documentElement.setAttribute(HTML_ATTRIBUTE, mode);
 
		return () => {
			document.documentElement.removeAttribute(HTML_ATTRIBUTE);
		};
	}, [theme.isLight]);
};