Reputation: 1
Hi I currently building an NextJS app. I want to implement the dark and light theme so I create a theme context which will store the app theme states(darkmode and lightmode).
ThemeContextProvider
.useState
as seen below.useState
data I have in the provider.toggleTheme
which is from the context
with setTheme
from the useState
.toggleTheme
fn from the context is not actually overrided with the setTheme
from the useState
so the theme data in the context will not be updated.
Can anybody tell me why this happened?
If you guys get confused please take a look at my codes belowHere's my theme-context code
import { createContext, useState } from "react";
const ThemeContext = createContext({
//false: lightmode, true: darkmode
theme: false,
toggleTheme: () => {},
});
export const ThemeContextProvider = (props) => {
//false: lightmode, true: darkmode
const [theme, setTheme] = useState(false);
const themeHandler = () => {
setTheme(!theme);
console.log("toggled!");
};
return (
<ThemeContext.Provider
value={{
theme,
toggleTheme: themeHandler,
}}
>
{props.children}
</ThemeContext.Provider>
);
};
export default ThemeContext;
Here's my toggle button
<button onClick={() => toggleTheme}>Toggle theme</button>
Upvotes: 0
Views: 171
Reputation: 110
Call the function
<button onClick={() => toggleTheme()}>Toggle theme</button>
Upvotes: 0