Imagine you’re building a React Application that stores data in a high-level
GrandParent component. In this application, you need to pass that data through a
Parent component, which then passes that data down to a
Child component to render.
This is a common and quite powerful pattern in React applications called “prop drilling”. Prop drilling is the term for when a piece of data is passed as a prop through a large number of components in a React application. The prop is “drilled” from a high-level component down through middle-level components down to a low-level component.
When props only have to be drilled through 1-2 components, prop drilling is a good strategy for making data available. However, when there are more layers to drill through, there may end up being many components that take in drilled props and pass down those props without ever using them. This can be a negative for two reasons:
- It bloats your code and makes it harder to understand or use the middle components.
- It causes middle components to re-render for changes to drilled props even if they don’t use those props themselves.
In this lesson, we’ll take a look at React’s Context API, a common approach to get around unnecessary prop drilling. Context is a feature of React that allows us to create a piece of state that any component within an area of your application can subscribe to.
By the end of the lesson, you’ll learn:
- How a React context provides shared state to React components
- Creating a context to provide a value to descendant React components
- Consuming that value in descendant React components
- Updating the context value in descendant React components
- Structuring nested providers for the same type of context
Let’s get started!
In this exercise and through the rest of this lesson, you’ll be modifying an existing React application. You’ll be changing its existing prop drilling of
theme values to share those values with context.
In your code editor, take a look at
ContactsApp.js. Here, you should see that the
theme prop is passed from a high-level
ContactsApp component and down through middle-level
ContactsList components. The
theme prop is finally used in the
ContactItem component. Let’s see how we can use React Context to minimize this prop drilling!