From the course: Building Production-Ready React Apps: Setup to Deployment with Firebase

Create a context object

- [Instructor] In a typical React application, data is passed from top to bottom, from parents to child, via the props. It can be very tedious for certain type of props that are required by many components within an application. For example, local preferences and UI settings. So the more complex the application, the more complex will be the communication between components. Imagine that you have multiple levels in your application, passing down data needs to be done manually through every component level from top to bottom, which can be very difficult to maintain. The solutions to this is the Context API. The Context API provides a way to share values without having to explicitly and manually pass props from the parents to the child components. So why use a Context object? The Context API is designed to share global data with several components, allowing all components to subscribe to a single source of truth. And so the React Context API allows to easily avoid a common problem, which is props-drilling, which is when you keep your data in one location and at the top level of the application tree. Instead, you want to use global data and a single source of truth, and we're going to do that by using a Context object. So let's see how we can refactor our app and use the Context API instead. So first, we're going to use this method from the React library, and we're going to create a new Context object. So let's go back to the Exercise Files. We're going to use the same Exercise Files, chapter 4. And here in the src directory, you're going to go ahead and create a new file, and I'm going to name this one context. And what we do is import createContext from react. And so the first step is to create a new Context object with createContext. Here we go. So there are five steps to using React Context. First, we create a context with the createContext method. Next, we're going to create a Provider component. So that's going to be the second step. And we're going to use this one to wrap around the root components of our application, like this example, like so. So that's going to be a third step. And we're going to use this prop, this Provider component takes just one prop, we're going to use this prop to pass down every global values we want to share with multiple components across the application. So coming next, we're going to see how we can create a Provider component. So stay tuned.

Contents