Created
April 10, 2021 14:27
-
-
Save salmanx/10e94d8ec280f9f45ecd6a5b447beabb to your computer and use it in GitHub Desktop.
Reduce prop drilling with React context
This file contains hidden or 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
// src/App.js | |
import React from "react"; | |
const UserContext = React.createContext(); | |
export default function App() { | |
const user = { name: "Reed" }; | |
return ( | |
<UserContext.Provider value={user}> | |
<main> | |
<Navbar title="My Special App" /> | |
<FeaturedPosts /> | |
</main> | |
</UserContext.Provider> | |
); | |
} | |
// src/components/Navbar.js | |
function Navbar({ title }) { | |
const user = React.useContext(UserContext); | |
return ( | |
<div> | |
<h1>{title}</h1> | |
{user && <a href="/logout">Logout</a>} | |
</div> | |
); | |
} | |
// src/components/FeaturedPosts.js | |
function FeaturedPosts() { | |
const posts = useFetchPosts(); | |
const user = React.useContext(UserContext); | |
if (user) return null; | |
return ( | |
<ul> | |
{posts.map((post) => ( | |
<li key={post.id}>{post.title}</li> | |
))} | |
</ul> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment