Introduction to the Context API

In this lesson, we’ll cover the Context API, which allows different pages, such as dashboard and profile, to use the same user data once the user logs in.

What is the Context API?

We need props to pass data or states to child components. However, as an application becomes more extensive and more complex in terms of number of components and amount of data, managing the states between child components becomes more difficult.

The Context API provides a way to pass data through the component tree without having to pass the props manually in each child component. The Context API is used when there’s data or a global state for the component tree, such as a username or an authenticated state.

Using the Context API

Steps to create and use the context API,

The steps to create and use the Context API are as follows:

  1. Create a Context using the React.createContext() method.
  2. The Context object that we created in the first step comes with a Provider React component that allows consuming components to subscribe to context changes. We use this Provider to wrap all the components that need to share their state or data with a Context.Provider.
  3. The Provider component takes a value as a prop so that we can pass any data or state between the wrapped components within the Provider component.
  4. Like the Provider component, the Context object also provides the Consumer component, which lets us subscribe to a context within a function component. We use Context.Consumer to read and access the Provider’s value.
  5. Here, each component that uses Context.Consumer is subscribed to Context changes. Whenever changes happen inside the Provider’s value, the value inside the component will also change.

In the following image, there are four rendered components inside the App component. These components are Dashboard, Profile, Login, and Home. We’ve wrapped all these components within the Context.Provider, which stores the data that we want to share between these four components. This is also known as the Global State.

Each of these components has a separate Context.Consumer to read and access the Global State. Each such Context.Consumer is subscribed to the Context object. Whenever any change happens in the Global State value of the Provider component, this change will reflect on these components as well.

Get hands-on with 1200+ tech skills courses.