Rizky Firman
Rizky Firman

Reputation: 1

Can't override Context API with useState updating function in NextJS

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).

My current solutions

  1. I use true-false data type to represent the dark and light mode.
  2. true is for dark and false is for light. Default is false.
  3. To toggle the theme, I create a function for it
  4. I create context provider component directly in the same file. It's called ThemeContextProvider.
  5. To update the context data, I'm using useState as seen below.
  6. With that logic, I pass the context value with the useState data I have in the provider.
  7. I override the toggleTheme which is from the context with setTheme from the useState.
  8. I'm triggering the toggleTheme fn in the navigation bar(toggle button).

My expectation

  1. Whenever I click the toggle button, the 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 below

Here'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

Answers (1)

Chigozie Ijomah
Chigozie Ijomah

Reputation: 110

Call the function

<button onClick={() => toggleTheme()}>Toggle theme</button>

Upvotes: 0

Related Questions