Skip to content

Instantly share code, notes, and snippets.

@leighhalliday
Created February 19, 2020 13:42
Show Gist options
  • Save leighhalliday/0b3641ab034b82055fb533222bfa89ea to your computer and use it in GitHub Desktop.
Save leighhalliday/0b3641ab034b82055fb533222bfa89ea to your computer and use it in GitHub Desktop.
React Context Rendering Demo
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