...

/

Testing the useContext Hook

Testing the useContext Hook

Learn how React context simplifies user data access and updates across components.

Application structure

Context is fun to use and has quite a few common applications. Let's consider a site with a user logo displayed at the top-right corner of the screen:

Press + to interact
An application with App, Header, and Logo
An application with App, Header, and Logo

The site is created with an App component, containing Header and Main. And in turn, Header contains Logo, and Site contains Greeting. The App, Header, and Logo are defined as follows:

function App({ initialUser }) {
// Set the user object initially
const user = initialUser;
// Render the Header and Main components, passing the user object
return (
<div>
<Header user={user} />
<Main user={user} />
</div>
);
}
// Header component: Displays the logo
const Header = ({ user }) => {
// Render the Logo component, passing the user object
return <Logo user={user} />;
}
// Logo component: Displays the user logo and the username
const Logo = ({ user }) => {
return (
<div>
<img src={user.imageUrl} alt="User Logo" />
<span>{user.username}</span>
</div>
);
}

Assuming the user gets authenticated as an initialUser and sent to the App, it gets passed via a prop to Header and Logo. In Logo, it gets consumed by its imageUrl property and username to display a logo. Notice the interface for all components needs to carry user as a prop. Since we want to display a greeting message under Main, the user needs to be passed via a prop as well. ...