perf: memoize ThemeProvider

This commit is contained in:
Phi
2019-09-17 17:03:43 -04:00
committed by Jean-Philippe Sirois
parent ce38236ed5
commit d61c218657
+17 -6
View File
@@ -1,4 +1,4 @@
import React, { createContext } from "react"
import React, { createContext, useMemo } from "react"
import { ThemeProvider as BaseThemeProvider } from "styled-components"
import { darkTheme, lightTheme } from "./design/themes"
@@ -19,14 +19,25 @@ export const ThemeContext = createContext<IThemeContext | null>(null)
const ThemeProvider = ({ children }: IThemeProviderProps) => {
const [theme, setTheme] = useLocalStorage("theme", "light")
const themeObject = theme === "dark" ? darkTheme : lightTheme
const toggleTheme = () => {
setTheme(theme === "light" ? "dark" : "light")
}
const themeObject = useMemo(
() => (theme === "dark" ? darkTheme : lightTheme),
[theme]
)
const contextValue = useMemo(
() => ({
theme,
setTheme,
toggleTheme: () => {
setTheme(theme === "light" ? "dark" : "light")
},
}),
[theme, setTheme]
)
return (
<ThemeContext.Provider value={{ theme, setTheme, toggleTheme }}>
<ThemeContext.Provider value={contextValue}>
<BaseThemeProvider theme={themeObject}>{children}</BaseThemeProvider>
</ThemeContext.Provider>
)