From 9f0f6e96775dfc8662e14651efae42510eb4ec0d Mon Sep 17 00:00:00 2001 From: PhilReact Date: Sat, 26 Apr 2025 12:44:52 +0300 Subject: [PATCH] save theme to localstorage for persistance --- src/components/Theme/ThemeContext.tsx | 38 +++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/src/components/Theme/ThemeContext.tsx b/src/components/Theme/ThemeContext.tsx index 5a5abb8..d2e7048 100644 --- a/src/components/Theme/ThemeContext.tsx +++ b/src/components/Theme/ThemeContext.tsx @@ -1,4 +1,11 @@ -import { createContext, useContext, useState, useMemo } from 'react'; +import { + createContext, + useContext, + useState, + useMemo, + useEffect, + useCallback, +} from 'react'; import { ThemeProvider as MuiThemeProvider } from '@mui/material/styles'; import { darkTheme } from '../../styles/theme-dark'; import { lightTheme } from '../../styles/theme-light'; @@ -17,9 +24,36 @@ export const ThemeProvider = ({ children }: { children: React.ReactNode }) => { ); const toggleTheme = () => { - setThemeMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light')); + setThemeMode((prevMode) => { + const newMode = prevMode === 'light' ? 'dark' : 'light'; + + const themeProperties = { + mode: newMode, + }; + + localStorage.setItem('saved_ui_theme', JSON.stringify(themeProperties)); + + return newMode; + }); }; + const getSavedTheme = useCallback(async () => { + try { + const themeProperties = JSON.parse( + localStorage.getItem(`saved_ui_theme`) || '{}' + ); + + const theme = themeProperties?.mode || 'light'; + setThemeMode(theme); + } catch (error) { + console.log('error', error); + } + }, []); + + useEffect(() => { + getSavedTheme(); + }, [getSavedTheme]); + return ( {children}