I saw an example code for creating theming in React using Context API. The theme Context was defined like:
import {createContext} from “react”; const ThemeContext = createContext([“light”, () => {}]); console.log(createContext); export default ThemeContext;
As can be seen, it takes an empty arrow function as the second item for the initial state. I also know we can also use Function.prototype or function () {}.
This is the ThemeToggler used to change the theme:
import React,{useContext} from “react”; import ThemeContext from “../Context/ThemeContext”; const themeTogglerStyle = { cursor: “pointer” } const ThemeToggler = () => { const[themeMode, setThemeMode] = useContext(ThemeContext); return( <div style = {themeTogglerStyle} onClick = {() => {setThemeMode(themeMode === “light”? “dark”: “light”)}}> // ***I have doubt in this line*** <span title = “switch theme”> {themeMode === “light” ? “🌙” : “☀️”} </span> </div> ); } export default ThemeToggler;
What I couldn’t understand was how the onClick function is calling this function prototype/empty function, and how does it update the value? It’s not like we’re using useState here so how can we update the value?
submitted by /u/God_Killer_01
[link] [comments]
Permanent link to this post here
