What is Context API?

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.

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

Does it 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:
  1. Overhead - Why should I create/update 3 files just to add one tiny feature?
  2. 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.

#react #redux #react hooks #api

What Is React Context API and How To Use It Best
22.50 GEEK