Created
February 26, 2023 18:57
-
-
Save paulwongx/c8fa6e58f4a558bfa329e07d0baa795e to your computer and use it in GitHub Desktop.
React Theme Provider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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