Global Context Pattern

Follow along with code examples here!

Table of Contents:

Global Context Design Pattern

The illustration above shows how we can wrap the _entire_ App component in our context, but in the example we only wrap the PostList component.

If we import the InstagramContext into main.jsx and render the InstagramContext.Provider around the App component...

...we run into an issue - what value do we provide?

The state values that we want to provide (incrementTotalLikes) lives in the App component. We can't lift that state up to the main.jsx file because there isn't a component here!

Wrapping the App component is common, and there is a common solution:

1) Create a ContextProvider wrapper component

We start by creating a new "wrapper-style" component that imports the Context object and renders its .Provider.

  • All of the global state for this application can be managed by this component.

  • Note how the children prop is used. This will become clearer next.

2) Import and Render the ContextProvider component in main.jsx

It is easier to see how InstagramContextProvider is a wrapper by looking at how it is used:

It is literally wrapped around the App component which is automatically provided to InstagramContextProvider as its children prop.

3) Refactor other components as necessary

With this change, the rest of our components that previously needed to manage state become greatly simplified:

Our App now is just a container for Header and PicturesList

Our Header previously needed to take in a totalLikes prop. Now, it retrieves it from InstagramContext.

However, there is still room for other pieces of state that can be managed more "locally":

Last updated