React Context API  –  A Replacement for Redux?



With React is urging us to migrate to the new Context API. Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In React, data is often passed from a parent to its child component as a prop.
This method has worked well in the past, but is not suitable for every kind of data. It will make things difficult later when moving components around. props even get passed down to child components which aren’t using the data.



Is Context API a new thing?

The truth is that Context has been a part of React for a really long time.

Remember the <Provider> tag that we used earlier in the Redux app? It is actually a part of the older React Context API. React Context API is even used by libraries such as react-redux, MobX-react, react-router, and glamorous.

So why is React Context API making such a big noise now?

React used to discourage developers from directly using it in their apps and it was only included on an experimental basis. Now, with official support + the ability to render props, Context brings us a delightful new experience.

How to use this new version of Context?

The new context API consists of three main steps:

  • ·         React.createContext is passed the initial value. It returns an object with a Provider and a Consumer.
  • ·         The Provider component is used higher in the tree and accepts a prop called value. This value can be anything!
  • ·         The Consumer component is used anywhere below the Provider in the tree and accepts a prop called children and must be a function that can accept a value and return a JSX.

Let’s take an in-detail look at how to use React Context API by migrating the earlier app from Redux to React Context API.


Comments

Popular posts from this blog

Hire Top AngularJS Development Companies & Developers

Quickly Create Real Angular Prototypes Without Writing Code

Python’s Fake Increment and Decrement Operators