Skip to content

Instantly share code, notes, and snippets.

@YDrogen
Last active November 22, 2023 11:26
Show Gist options
  • Save YDrogen/3f58ee0141e554695dd0a16eb86f2413 to your computer and use it in GitHub Desktop.
Save YDrogen/3f58ee0141e554695dd0a16eb86f2413 to your computer and use it in GitHub Desktop.
A React theme provider which stores the current theme in the localStorage
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
type Theme = 'system' | 'light' | 'dark';
type ThemeProviderProps = {
readonly children: React.ReactNode;
readonly defaultTheme?: Theme;
readonly storageKey?: string;
};
type ThemeProviderState = {
theme: Theme;
setTheme: (theme: Theme) => void;
};
const ThemeProviderContext = createContext<ThemeProviderState | undefined>(
undefined,
);
export function ThemeProvider({
children,
defaultTheme = 'system',
storageKey = 'vite-ui-theme',
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(
() => localStorage.getItem(storageKey) || defaultTheme,
);
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
.matches
? 'dark'
: 'light';
root.classList.add(systemTheme);
return;
}
root.classList.add(theme);
}, [theme]);
const value = useMemo(
() => ({
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme);
setTheme(theme);
},
}),
[theme, storageKey],
);
return (
<ThemeProviderContext.Provider {...props} value={value}>
{children}
</ThemeProviderContext.Provider>
);
}
export const useTheme = () => {
const context = useContext(ThemeProviderContext);
if (!context) throw new Error('useTheme must be used within a ThemeProvider');
return context;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment