Created
February 19, 2020 13:42
-
-
Save leighhalliday/0b3641ab034b82055fb533222bfa89ea to your computer and use it in GitHub Desktop.
React Context Rendering Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
const MyContext = React.createContext(); | |
const MyProvider = ({ children }) => { | |
const [theme, setTheme] = React.useState("light"); | |
const nextTheme = theme === "light" ? "dark" : "light"; | |
const value = { | |
theme, | |
nextTheme, | |
toggleTheme: () => { | |
setTheme(nextTheme); | |
} | |
}; | |
return <MyContext.Provider value={value}>{children}</MyContext.Provider>; | |
}; | |
function App() { | |
return ( | |
<MyProvider> | |
<DirectChild /> | |
</MyProvider> | |
); | |
} | |
const DirectChild = () => { | |
console.log("DirectChild"); | |
return ( | |
<nav> | |
<DeeperChild /> | |
</nav> | |
); | |
}; | |
const DeeperChild = () => { | |
console.log("DeeperChild"); | |
const { nextTheme, toggleTheme } = React.useContext(MyContext); | |
return ( | |
<div> | |
<button onClick={toggleTheme}>{nextTheme}</button> | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment