If you want to change Context value while using React Hook of useContext? The argument passed to createContext will only be the default value if the component that uses useContext has no Provider above it further up the tree. You could instead create a Provider that supplies the style and visibility as well as functions to toggle them.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | const { createContext, useContext, useState } = React; const ThemeContext = createContext(null); function Content() { const { style, visible, toggleStyle, toggleVisible } = useContext( ThemeContext ); return ( <div> <p> The theme is <em>{style}</em> and state of visibility is <em> {visible.toString()}</em> </p> <button onClick={toggleStyle}>Change Theme</button> <button onClick={toggleVisible}>Change Visibility</button> </div> ); } function App() { const [style, setStyle] = useState("light"); const [visible, setVisible] = useState(true); function toggleStyle() { setStyle(style => (style === "light" ? "dark" : "light")); } function toggleVisible() { setVisible(visible => !visible); } return ( <ThemeContext.Provider value={{ style, visible, toggleStyle, toggleVisible }} > <Content /> </ThemeContext.Provider> ); } ReactDOM.render(<App />, document.getElementById("root")); |
1 2 3 4 | <div id="root"></div> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.