Listing 17-8: Eliminating Prop Drilling with Context
import React, { useState, useContext } from "react";
const UserContext = React.createContext();
const App = () => {
const [username, setUsername] = useState();
if (username) {
return (
<>
<UserContext.Provider value={{ username, setUsername }}>
<Dashboard />
</UserContext.Provider>
</>
);
} else {
return <button onClick={() => setUsername("Chris")}>Login</button>;
}
};
const Dashboard = (props) => {
return <Header />;
};
const Header = (props) => {
return <UserControls />;
};
const UserControls = (props) => {
return (
<>
<WelcomeMessage />
<Logout />
</>
);
};
const WelcomeMessage = () => {
const { username } = useContext(UserContext);
return <>Welcome {username}!</>;
};
const Logout = (props) => {
const { setUsername } = useContext(UserContext);
return (
<button
onClick={() => {
setUsername("");
}}
>
Logout
</button>
);
};
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.