martinms

Untitled

Oct 5th, 2025
545
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.54 KB | None | 0 0
  1. "use client";
  2.  
  3. import type React from "react";
  4. import { createContext, useState, useContext, useEffect } from "react";
  5.  
  6. type Theme = "light" | "dark";
  7.  
  8. type ThemeContextType = {
  9.   theme: Theme;
  10.   toggleTheme: () => void;
  11. };
  12.  
  13. const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
  14.  
  15. export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({
  16.   children,
  17. }) => {
  18.   const [theme, setTheme] = useState<Theme>("light");
  19.   const [isInitialized, setIsInitialized] = useState(false);
  20.  
  21.   useEffect(() => {
  22.     // This code will only run on the client side
  23.     const savedTheme = localStorage.getItem("theme") as Theme | null;
  24.     const initialTheme = savedTheme || "light"; // Default to light theme
  25.  
  26.     setTheme(initialTheme);
  27.     setIsInitialized(true);
  28.   }, []);
  29.  
  30.   useEffect(() => {
  31.     if (isInitialized) {
  32.       localStorage.setItem("theme", theme);
  33.       if (theme === "dark") {
  34.         document.documentElement.classList.add("dark");
  35.       } else {
  36.         document.documentElement.classList.remove("dark");
  37.       }
  38.     }
  39.   }, [theme, isInitialized]);
  40.  
  41.   const toggleTheme = () => {
  42.     setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
  43.   };
  44.  
  45.   return (
  46.     <ThemeContext.Provider value={{ theme, toggleTheme }}>
  47.       {children}
  48.     </ThemeContext.Provider>
  49.   );
  50. };
  51.  
  52. export const useTheme = () => {
  53.   const context = useContext(ThemeContext);
  54.   if (context === undefined) {
  55.     throw new Error("useTheme must be used within a ThemeProvider");
  56.   }
  57.   return context;
  58. };
  59.  
Advertisement
Add Comment
Please, Sign In to add comment