DEV Community

Kazi Abdur Rakib
Kazi Abdur Rakib

Posted on

What is Context API? React context API: How it works? Context API will replace redux?

What is Context API?
The React Context API is a way for a React app to effectively produce global variables that can be passed around. This is the alternative to "prop drilling" or moving props from grandparent to child to parent, and so on. Context is also touted as an easier, lighter approach to state management using Redux.
Context API is a (kind of) new feature added in version 16.3 of React that allows one to share state across the entire app (or part of it) lightly and with ease.
**
React context API: How it works?**
React.createContext() is all you need. It returns a consumer and a provider. Provider is a component that as it's names suggests provides the state to its children. It will hold the "store" and be the parent of all the components that might need that store. Consumer as it so happens is a component that consumes and uses the state. More information can be found on React's documentation page

Context API will replace redux?
No. Well, not entirely.
Redux is great and came perfectly to answer the need for state management. Actually, it answered this need so well that it came to be known that you can't be a "true" React developer if you don't know your way around Redux. However, Redux has its disadvantages, and that's why it's important to know what Context API gives us that Redux doesn't:
Simplicity - When using redux people tend to manage almost all of their state in redux and it causes 2 problems:

Overhead - Why should I create/update 3 files just to add one tiny feature?
One of the significant advantages of React's one-way data binding is that it's easy to understand - A component passes state to its children. Using Redux takes it away from us.
Using Context API we can define several unrelated contexts (stores) and use each in its proper place in the app.

Top comments (0)