All files / contexts ThemeContext.jsx

94.73% Statements 18/19
90% Branches 9/10
100% Functions 6/6
94.44% Lines 17/18

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    2x     20x 15x 15x         20x 20x   20x 12x   8x     20x     20x 5x     20x               46x 46x 4x   41x    
import { createContext, useContext, useEffect, useState } from "react"
 
const ThemeContext = createContext()
 
export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState(() => {
    Eif (typeof window !== "undefined") {
      return localStorage.getItem("theme") || "dark"
    }
    return "dark"
  })
 
  useEffect(() => {
    const root = window.document.documentElement
    
    if (theme === "dark") {
      root.classList.add("dark")
    } else {
      root.classList.remove("dark")
    }
    
    localStorage.setItem("theme", theme)
  }, [theme])
 
  const toggleTheme = () => {
    setTheme(prev => prev === "dark" ? "light" : "dark")
  }
 
  return (
    <ThemeContext.Provider value={{ theme, setTheme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  )
}
 
export function useTheme() {
  const context = useContext(ThemeContext)
  if (!context) {
    throw new Error("useTheme must be used within ThemeProvider")
  }
  return context
}