Skip to main content
- Class Components
- The React Lifecycle
- Composing and Sharing Non-Visual Behavior
- Testing Web Applications
- Class Components
- The React Lifecycle
- Composing and Sharing Non-Visual Behavior
- Testing Web Applications
In your typical react application state is passed top-down (parent to child) via props, but this can become very cumbersome quickly, especially when those props are required by many components across your application. However with the introduction of reacts Context API you no longer have to pass props down from component to component - what React devs call “prop drilling”. We can now store data on a context object, and retrieve that data in the necessary components from the context object, not props!
At the end of this module, you should be able to:
- describe what the Context API is and the problem is solves
- provide data to the component tree with a context provider
- consume data from a context object in nested components
A witty saying proves nothing.
Voltaire
Review each preclass resource before class.
Context is a great tool to simplify state management. We will see how it helps us manage state easier as our apps begin to scale.
The React docs give us a good explanation of what Context is:
In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.
We use the Context API when we have global data that lots of components share (things like user or theme), or when we have to pass data through intermediate components. The API can help keep your state relatively clean.
One caveat here is that it can make components harder to reuse. Another architectural pattern you may want to look at is component composition.
Read through this article and write out a simple explanation of what context is. Send your explanation to your TL in Slack.
Read through the Context API docs and explain to someone in your TL group what the Provider and Consumer methods are.
So knowing that React’s Context API gives us a new way to pass data around, how does it do it? We will learn about two methods that a context object comes with - a Provider and a Consumer.
Context API allows us to create what’s known as a Context Object.
import { createContext } from 'react';
const ContextObject = createContext();
// usually we'll name the object by the data it will hold - ie UserContext, or MoviesContext, etc...
This object gives us two important components to work with a ContextObject.Provider and a ContextObject.Consumer.
The Provider method accepts a single prop called value, the value prop is used to provide our data across our app.
<ContextObject.Provider value={dataToPassDown}>
<NestedComponent />
<OtherNestedComponent />
</ContextObject.Provider>
The context Consumer consumes and returns the value provided by the Provider.
So how do we utilize Context API? First, follow along at this link here.
Your app should look like this at first glance.
Diving into the code, you’ll notice we’re bringing in two hooks from the react library useState and useEffect.
The useState hook holds and sets user state. The useEffect hook performs a pseudo API call that sets “my user” to state.
You’ll also notice a User component rendering Name goes here as a placeholder.
Now that we have that out of the way, let’s talk about the goal we want to achieve. We want to be able to provide data to the child component (based on user data sitting in state) and consume it, using Context API.
The first thing we need to do is make a new folder named contexts. This folder is going to hold all the context objects we create.
-
Inside that folder we’re need to create a new file named
UserContext.js. This is where we’re going to create our first context object! -
Inside that file, we’re going to create our
UserContext.import { createContext } from 'react'; export const UserContext = createContext();
Now you may be thinking wow! Only two lines of code? Yep! Only two lines of code and we have successfully created our UserContext.
Now that we have created our UserContext let’s import it into our index.js.
import { UserContext } from '../contexts/UserContext';
After creating and importing our UserContext we can start providing our user data across our application.
To do so, we need to wrap all of our child components inside of our UserContext Provider and pass it a prop of value, this prop contains our user state.
return (
<UserContext.Provider value={user}>
<div className="container">
<User />
</div>
</UserContext.Provider>
);
Doing so, we allow all child components of our UserContext Provider to consume the value(s) that come from the hook, in our case, the value is a user object.
Using an old project, go in and add a context item for some of the state there. Then pass the data into the context provider.
Once we have set up a context provider, we will need to know how to consume the data passed into it.
Consuming the data passed into the provider is the final step for using the Context API. We will use a context hook for this, though keep in mind that you can use render props as well.
import { useContext } from 'react'
import { ContextObject } from '../contexts';
...
// inside the component
const myData = useContext(ContextObject);
// or you can destructure the data like this:
const { someData, moreData } = useContext(ContextObject);
Now you’re ready to use the data in your component!
In the previous objective, we created our UserContext hook, and passed our data into the provider. Now it’s time to consume it.
To do so import the useContext hook from the react library and our UserContext.
import React, { useContext } from 'react';
import { UserContext } from '../../contexts/UserContext';
After importing our UserContext, we will consume the data from it.
const user = useContext(UserContext);
Finally, we can render our user to the screen!
return (
<div className="profile">
<p>
{user.lastName}, {user.firstName}
</p>
</div>
);
Our app should look like this if everything is correct.
The completed follow along code can be found here
Continue working in the app you chose in the last objective. Now that you have rendered the context provider, and passed in your data, you need to consume that data where it’s needed.
-
In this project you’ll take take an existing e-commerce store and refactor the application to use the Context API.
You can use class recordings to help you master the material.
To demonstrate mastery of this module, you need to complete and pass a code review on each of the following:
-
Objective challenge:
Read through the Context API docs and explain to someone in your TL group what the Provider and Consumer methods are.
-
Objective challenge:
Using an old project, go in and add a context item for some of the state there. Then pass the data into the context provider.
-
Objective challenge:
Continue working in the app you chose in the last objective. Now that you have rendered the context provider, and passed in your data, you need to consume that data where it’s needed.
-
Project: React Shopping Cart

