Jawad Ali
Jawad Ali

Reputation: 71

Why we use Context API in ReactJs? What will happen if we use simple props?

My Question is Why we use Context API in ReactJs? I know the answer a little but the concept is not clear. For Example, we have 4 components like (compA, compB, compC, compD) to pass data from compA to compD we use context API because we don't want to pass our data through in between components but we can achieve our goal by importing compD in compA and pass props from compA to compD. Then why we use context API?

Upvotes: 0

Views: 207

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370879

but we can achieve our goal by importing compD in compA and pass props from compA to compD

From a code organization perspective, this only works if it makes sense that compA directly manages compD. Often, this is not the case.

For example, let's say compA is the whole application component, and compB is the header, and compC is a menu in the header, and compD is a menu item. It doesn't make sense for the top component to import every single little component that needs the top component's state; the top component would quickly become unwieldly huge and hard to manage.

Using the Context API allows for the separation of responsibilities without having to manually pass down everything through props.

Upvotes: 2

Related Questions