Skip to content

Instantly share code, notes, and snippets.

@salmanx
Created April 10, 2021 14:27
Show Gist options
  • Save salmanx/10e94d8ec280f9f45ecd6a5b447beabb to your computer and use it in GitHub Desktop.
Save salmanx/10e94d8ec280f9f45ecd6a5b447beabb to your computer and use it in GitHub Desktop.
Reduce prop drilling with React context
// 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