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:
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 initiallyconst user = initialUser;// Render the Header and Main components, passing the user objectreturn (<div><Header user={user} /><Main user={user} /></div>);}// Header component: Displays the logoconst Header = ({ user }) => {// Render the Logo component, passing the user objectreturn <Logo user={user} />;}// Logo component: Displays the user logo and the usernameconst 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. ...