Skip to content

Instantly share code, notes, and snippets.

@paulwongx
Created February 26, 2023 18:57
Show Gist options
  • Save paulwongx/c8fa6e58f4a558bfa329e07d0baa795e to your computer and use it in GitHub Desktop.
Save paulwongx/c8fa6e58f4a558bfa329e07d0baa795e to your computer and use it in GitHub Desktop.
React Theme Provider
"use client"
import React, { useState, SetStateAction, Dispatch } from "react";
import { Color, colors } from "@/types"
import { useIsomorphicLayoutEffect } from "usehooks-ts";
interface ThemeContextProps {
theme: Color;
setTheme: Dispatch<SetStateAction<Color>> | null;
}
const ThemeContext = React.createContext<ThemeContextProps>({
theme: "blue",
setTheme: null
});
// Create a React theme provider component
function ThemeProvider ({ children }: { children: React.ReactNode | React.ReactNode[] }) {
const [theme, setTheme] = useState<Color>("blue");
const setLocalStorage = (theme: Color) => {
window.localStorage.setItem('theme', theme);
setTheme(theme);
};
useIsomorphicLayoutEffect(() => {
const localTheme = window.localStorage.getItem('theme');
if (localTheme && colors.includes(localTheme as any)) {
setTheme(localTheme as Color);
}
}, []);
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
)
}
const useTheme = () => React.useContext(ThemeContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment