What is Context API(Redux alternative)

Shakya Peiris
2 min readMay 21, 2021

Hey wassup! Hope you are reacting well. Today let’s discuss what is Context API in react. If you are using redux you must have used it in earlier days. If not no problems let’s learn it today.

If you are a beginner you might be thinking what the hell is this redux? Redux is an application wide state management tool and the duty of the context API is also the same.

If you are building low frequency app context API may be the best option. But it doesn’t work in high frequency application. That’s the place where redux comes to action! But you must learn this since it was recommended by people working in react and they say that in their projects they still use this tool.

Before going deep in to context API I invite you to checkout a single page food ordering app developed by me where context API does a great job in managing pages and cart. Refer following links for code and app.

App Link and Code

So before start coding you have to make a store folder inside your components folder and name it as you wish.

Basically there are 3 parts in a context,

  1. Store
    Store is basically an object.
  2. Provider
    Provider lies on the uppermost level of the component tree. So that it could provide the state to the whole application.(Normally inside index.js file as a wrapper). Also application can only trigger the values in side using provider. But if you make another component inside the store page as follows, it will be highly effective.
  3. Consumer (Subsriber in redux)
    Consumer must on lie parallely with the consumer. We can use useContex hook to work with the consumer. If you are using class based component you have to use storeName.Consumer component.

Then we could wrap the App component as follows.

Then how can we use the consumer components with useContext hook? Look down!

So, that’s it and hope you have learned a new thing! Thank You

--

--