Site icon NodeXperts

Context API

Why context? Is it easy to use? Why is context so powerful?

Context is so powerful, why do developers use Context and what kind of problems Context resolves.

Let’s assume that we have to create an E-Commerce Application. We have an app that has Setting, Auth and Orders children.

Auth has children sign in and sing out. On the left side we have some kind of Settings page. Their child is a user page and the user has a Profile page. Similarly, on the right side there is an Order page which keeps track of order history and also returns user that had made.

Now, we will get the information about the user from Sign in and Sign up, when the user enters their information.

In the left side Profile needs the information of users.

For doing so, we first have to figure out which has the top level parent dominator.

That is an App.

Only from the app, we can props down and access these components. Because, sign in and sign out can’t directly pass the information of users to their siblings which is profile or history or returns.

For that we can move data up to the parent. But that will be very costly.

First we have to go to the Auth, then App. From App go to the Settings then Users then finally go to the Profile (which needs data). Similarly from the right side also.

But here is the main thing that other components don’t need the user data. They all serve as a traffic made node module. At the end it is just a path.

And the way it passes is through props. That is why this is actually something known as props drilling.

These props for all these for all these intermediate components that don’t even need that data in the first place.

For Example:- app doesn’t need the user data neither setting and user similarly on right side also order doesn’t need the data.

Imagine, what happens if there is a storage and we can access the storage from anywhere without props.

And then once there are some nodes which need the data, it can directly pass it over to the corresponding nodes.

No need for any props drilling, no need to send the data for the component which doesn’t need the user data.

This is exactly what React Context allows us to do. It allows us to store the data somewhere. So, we don’t need props drilling and get data directly from the context.

From the above example we understood what the React Context is all about and how it helps to tackle situations like prop-drilling and effective communication of state data.

Exit mobile version