Context API: What and Why?
Nitin Singh
Posted on December 30, 2023
Wanted to share my learning related to Context API.
Before going into what Context API is, we need to understand why there was a need for it.
Let's take an example:
Imagine an web app with a homepage featuring a dashboard. The dashboard is divided into two parts: the left and right sides. The right side further divides into an upper and lower part, with a card component in the upper part.
In the card component, we require a title. Let's assume we are fetching data from an API, and the title comes from this API. The title, initially received from the API, first pass to the App component, then moves to the dashboard component, followed by the right side, and then progresses to the upper side component. Finally, it reaches the card component.
In this process, the data is passed through different components to reach its original destination. All these data pass-on are inefficient and not an optimized way of handling this.
To address this issue, we can create a global object that stores all the necessary data or the fetched data required by different components of the app.
This is where the Context API comes into play.
Think of the Context API as a global object where different data or Fetched data can be stored, and this data can then be directly accessed by specific components.
Using the Context API can make handling data and managing states in React apps simpler. This is especially helpful when different parts of your app need to use the same data.
Posted on December 30, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.