All files / benchmark/src usePersistentTheme.ts

88.88% Statements 16/18
70% Branches 7/10
100% Functions 7/7
87.5% Lines 14/16

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 30 31 32 33 34 35 36 37 38 39 40 41 42 43        1x     18x       18x 18x       19x       19x 19x       66x   66x 18x 18x     66x 3x     66x            
import { useCallback, useEffect, useState } from "react";
 
export type ThemeMode = "light" | "dark";
 
export const THEME_STORAGE_KEY = "frontend-performance-lab-theme";
 
export function readStoredTheme(storageKey = THEME_STORAGE_KEY): ThemeMode {
  Iif (typeof window === "undefined") {
    return "light";
  }
 
  const stored = window.localStorage.getItem(storageKey);
  return stored === "dark" ? "dark" : "light";
}
 
export function applyTheme(theme: ThemeMode): void {
  Iif (typeof document === "undefined") {
    return;
  }
 
  document.documentElement.dataset.theme = theme;
  document.documentElement.style.colorScheme = theme;
}
 
export function usePersistentTheme(storageKey = THEME_STORAGE_KEY) {
  const [theme, setTheme] = useState<ThemeMode>(() => readStoredTheme(storageKey));
 
  useEffect(() => {
    applyTheme(theme);
    window.localStorage.setItem(storageKey, theme);
  }, [storageKey, theme]);
 
  const toggleTheme = useCallback(() => {
    setTheme((current) => (current === "dark" ? "light" : "dark"));
  }, []);
 
  return {
    theme,
    isDark: theme === "dark",
    toggleTheme
  };
}