mirror of
https://github.com/Stone-Red-Code/website.git
synced 2026-09-07 16:06:12 +02:00
perf: memoize ThemeProvider
This commit is contained in:
committed by
Jean-Philippe Sirois
parent
ce38236ed5
commit
d61c218657
+17
-6
@@ -1,4 +1,4 @@
|
|||||||
import React, { createContext } from "react"
|
import React, { createContext, useMemo } from "react"
|
||||||
import { ThemeProvider as BaseThemeProvider } from "styled-components"
|
import { ThemeProvider as BaseThemeProvider } from "styled-components"
|
||||||
|
|
||||||
import { darkTheme, lightTheme } from "./design/themes"
|
import { darkTheme, lightTheme } from "./design/themes"
|
||||||
@@ -19,14 +19,25 @@ export const ThemeContext = createContext<IThemeContext | null>(null)
|
|||||||
|
|
||||||
const ThemeProvider = ({ children }: IThemeProviderProps) => {
|
const ThemeProvider = ({ children }: IThemeProviderProps) => {
|
||||||
const [theme, setTheme] = useLocalStorage("theme", "light")
|
const [theme, setTheme] = useLocalStorage("theme", "light")
|
||||||
const themeObject = theme === "dark" ? darkTheme : lightTheme
|
|
||||||
|
|
||||||
const toggleTheme = () => {
|
const themeObject = useMemo(
|
||||||
setTheme(theme === "light" ? "dark" : "light")
|
() => (theme === "dark" ? darkTheme : lightTheme),
|
||||||
}
|
[theme]
|
||||||
|
)
|
||||||
|
|
||||||
|
const contextValue = useMemo(
|
||||||
|
() => ({
|
||||||
|
theme,
|
||||||
|
setTheme,
|
||||||
|
toggleTheme: () => {
|
||||||
|
setTheme(theme === "light" ? "dark" : "light")
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
[theme, setTheme]
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ThemeContext.Provider value={{ theme, setTheme, toggleTheme }}>
|
<ThemeContext.Provider value={contextValue}>
|
||||||
<BaseThemeProvider theme={themeObject}>{children}</BaseThemeProvider>
|
<BaseThemeProvider theme={themeObject}>{children}</BaseThemeProvider>
|
||||||
</ThemeContext.Provider>
|
</ThemeContext.Provider>
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user