Skip to content

Commit

Permalink
fix: theme persistence
Browse files Browse the repository at this point in the history
  • Loading branch information
aldbr committed Dec 5, 2023
1 parent 864404b commit 0b5dd67
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/contexts/ThemeProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"use client";
import { useMediaQuery } from "@mui/material";
import { createContext, useState } from "react";
import { createContext, useEffect, useState } from "react";

/**
* Theme context type
* @property theme - the current theme mode
* @property toggleTheme - function to toggle the theme mode
*/
type ThemeContextType = {
theme: "light" | "dark";
theme: string;
toggleTheme: () => void;
};

Expand All @@ -30,12 +30,22 @@ export const ThemeContext = createContext<ThemeContextType | undefined>(
* ThemeProvider component to provide the theme context to its children
*/
export const ThemeProvider = ({ children }: ThemeProviderProps) => {
// State to manage the current theme mode
const [theme, setTheme] = useState<"light" | "dark">(
useMediaQuery("(prefers-color-scheme: dark)") ? "dark" : "light",
);
// Read the initial theme from localStorage
const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
const storedTheme = localStorage.getItem("theme");
const defaultTheme = storedTheme
? storedTheme
: prefersDarkMode
? "dark"
: "light";

const [theme, setTheme] = useState<string>(defaultTheme);

// Update localStorage when the theme changes
useEffect(() => {
localStorage.setItem("theme", theme);
}, [theme]);

// Function to toggle the theme mode
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
};
Expand Down

0 comments on commit 0b5dd67

Please sign in to comment.