All files / hooks useTheme.ts

100% Statements 12/12
100% Branches 6/6
100% Functions 3/3
100% Lines 11/11

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 281x             1x 6x       6x 6x 3x   3x   6x     6x 2x     6x    
import { useEffect, useState } from "react";
 
/**
 * Custom hook to manage theme (light/dark) in a React application.
 * It synchronizes the theme with localStorage and applies the theme to the document.
 * @returns {Object} - Contains the current theme and a function to toggle the theme.
 */
export const useTheme = () => {
  const [theme, setTheme] = useState(
    localStorage.getItem("theme") || "light"
  );
 
  useEffect(() => {
    if (theme === "dark") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
    localStorage.setItem("theme", theme);
  }, [theme]);
 
  const toggleTheme = () => {
    setTheme(theme === "dark" ? "light" : "dark");
  };
 
  return { theme, toggleTheme };
};