Skip to content

Instantly share code, notes, and snippets.

const Child = () => {
const { count, setCount } = React.useContext(CountContext);
return (
<div>
<Button onClick={() => setCount((count) => count)}>
Call setCount from context with same value
</button>
</div>
);
};
const Parent = () => {
return (
<Child />
);
};
const GrandParent = ({ children }) => {
return (
<div>{children}</div>
);
};
const CountContext = React.createContext(null);
const CountContextProvider = ({ children }) => {
const [count, setCount] = React.useState(0);
return (
<CountContext.Provider value={{ count, setCount }}>
<GrandParent>{children}</GrandParent>
</CountContext.Provider>
);
};
const Context = () => {
return (
<CountContextProvider>
<Parent />
</CountContextProvider>
);
};
const App = () => {
// ...
return (
<>
<Page /*...*/ >
<ShowComments comments ={ comments } />
</Page>
</>
);
};
const showComments = ({ comments }) => {
console.log("Comments is rendering");
return (
<ul>
{comments.map((comment) => (
<li key={comment}>{comment}</li>
))}
</ul>
);
};
const App = () => {
// ...
return (
<>
<Page /*...*/ >
{showComments({ comments })}
</Page>
</>
);
};
const Page = ({ user, children, onLogin, onAddComment }) => {
if (!user.isLoggedIn) {
return (
<Layout>
<h3>Please log in to see and post comments</h3>
<PasswordInput/>
<button onClick={onLogin}>Login!</button>
</Layout>
);
}
const PasswordInput = () => <input type="password" />;
const CommentInput = () => <input type="text" />;