More

    Everything About React Context

    What is React Context?

    The Context API landed in React in 16.3. Context is a way of creating a global application state which allows you to avoid having to pass props to different levels of the component tree.  Prop drilling is the act of having to pass props to individual levels of the component tree through other components that do not need that state. There’s been a lot of discussions now about “Is context a Redux killer?” and I wanted to address that really quickly by saying “NO!”.

    So, when is context useful? In smaller applications where redux may not make a lot of sense having a small stateful component at the top level of your application providing some context around users authentication c powerful but there are things

    that come along with Redux that are very helpful in larger applications such as a time-traveling debugger, the dev tools that surround Redux, the community of tools, plugins and things that come along with Redux. So, again it’s not a redux killer. It can be used alongside Redux and to augment your applications when Redux doesn’t make sense.

    A lot of you may not believe to hear that the Context API is nothing new. It’s actually been around for quite a while now does not in its current form.

    Origin

    React API: The Context API is a react API. It’s the part of the React library which means if you’ve ever implemented or imported the React library to any of your programs, you’ve actually had access to the Context API with a few lines of code, you could have the Context API running in your application.

    Been around since 2013: Context API has been around ever since React was open source back in 2013.

    Designed to reduce “prop drilling”: Context API takes the data and actually pass it into whatever components actually need it without having to pass all these things to the next components. It allows us to be able to inject that data at any level in our React API or in our React’s application at any moment of time.

    Problems with Context API

    Like a Global variable are best avoided when writing clear code, we should avoid using Context in most cases. Threading your data through the tree is much easier to understand. Even React’s own library suggests doing the same. Use of

    Redux became one of the most popular React’s libraries for state management. It filled the holes where the Context API was lacking.

    Why do people believe that the react context is the redux killer?

    React 16.3 came out in March 2018 and with that came this very exciting thing, the very first merge request for this new version of Context rather this new version of React was the new version of Context. It was completely revamped of the Context API which allowed us to actually do what the Context API set out for It allowed us to actually take that data from the top-level component with no outside libraries, no Redux, no MobX, and nothing. It actually uses React to pass that data down with nothing else.

    Implementation Patterns

    One of the most powerful things about the Context API is that it’s so damn flexible on the implementation. There are so many different techniques to put in place the API into the application.

     

    React JS: Here’s what we should know about it

    Fundamentals

     

    BASIC IMPLEMENTATION

    An example of a person ordering pizza to prove this setup of the Context API. We have Domino as our representation of our context instance. Remember throughout these examples that we’ve three building blocks for setting up our context system. So, the first one is our context instance that is represented by Domino’s and every context instance has its own delivery system aka, our context provider. Every provider is past something or passed some data like in our example we’re passing our provider a pizza. It’s going to transport it to our consumer.

    Since, the consumer is such a valuable customer for Domino’s as he orders from them so often even if their delivery person is super busy and there’s like 3-4 deliveries ahead of him, that pizza is still going to him first. These deliveries represent our intermediary react components that don’t need this data or this Pizza in our example. Our providers are not going to go through them, not gonna prop drill through them, it’s gonna go to the consumer. The code to tool the same is below:

    Many providers for One Component:

    CONTEXT DEFAULT VALUES;

    Using something called a default value in the Context API adds another layer of flexibility in our implementation.

     

    When to use Context?

    Context is in such that the data that it is global for a tree of React components. Such as the current authenticated user, theme, or preferred language can split. Using context, the passing of props using intermediate element could take no notice. It is used when any data would need to shared many components at various nesting levels. Context allows us to broadcast the data and lets us make changes to it along with all components after. Yet, it must be applied because it may make reuse of data difficult. If someone wants to avoid passing some props via many levels then a simpler solution would be content composition rather than Context. A few instances when using context is simpler than its alternatives. It includes managing the theme, current locale or the data cache.

     

    APIs to be used:

    React.createContext

    This is for creating a context object. When a component is rendered by React that is subscribed to this Context object the current context value would be read by it from the nearest similar Provider above it in the tree.

     

    Context.Provider

    This accepts a value prop that is to pass to be consuming components which are descendants of this particular Provider. There is a possibility of connecting one Provider with many consumers. It is possible to nest providers for consuming values deep within the tree.

     

    Class.contextType

    The property, contextType, could assign to a class that has a Context object created by React.createContext(). This allows us to consume the nearest current value of that Context type with the use of this context. This might reference in all the lifecycle methods which also includes the render function.

     

    Context.Consumer

    It’s a React component that subscribes to changing content. It allows us to subscribe to a context that is within a function component.

    A function comes as a child. The current context value received by the function and a React node return. The value argument that is being passed to the function must be the same as the value prop of the closest Provider above in the tree for this context. If there exists no Provider above for this context, the value argument must be the same as the defaultValue before passed to createContext().

     

    Context.displayName

    Using this, a displayName string property accepted by the Context object. The string used by React DevTools to determine what should come to display for the context.

     

    Steps:
    1. Initialize the Context

    First, the context needs to be created, which can be later used to create consumers and providers.

     

    1. Create the Provider

    Once the context initialization is over, the context could import and used to create the provider. States initialized with some values, which can share via a value prop to our provider component. So these methods are as reducers in Redux. These methods can be taken as reducers in Redux. To make sure the provider is accessible by components, the application has to wrap around it.

     

    1. Create the Consumer

    We are going to import the context one more time and wrap our component with it. This inserts the context’s argument in the component. After that it’s pretty simple, we can use context like props.

    Conclusion

    Throughout the article, we can see there are certain similarities between Redux and Context API. The big advantage of using Redux is the app we are creating something that can have a central store. Store from which any component in the app can access. But by using the Context API, we can have the functionality by default without shedding any extra sweat. There exist many rumors that Context API will render Redux obsolete.

    This might actually be correct for people who only use the central store capabilities of Redux. If that is the only one feature, one might now even replace Redux with Context API to avoid prop drilling without any need for third-party libraries

     

    Recent Articles

    React Fragment: Find out what we encountered.!

      React Fragment: Hello Devs, in my journey of learning react I came across some frontend conditions where I had to render multiple react components,...

    React Admin: Documentation | Features | Dahboard | Templates

      React Admin is a framework for the front-end development of data-driven applications. That is operating in a browser over the top of REST or...

    React Hooks

      A hook is a component that allows us to use the features of React and state without defining a class. This feature is added...

    React Animation: A definitive guide

    React Animations Add-ons The ReactTransitionGroup add-on is a lower-level Applications Program Interface (API) component for creating react animations. And the ReactCSSTransitionGroup, is a component used...

    Create React App: A Complete guide for Beginners

      Create React App is the modern way of building an official Single Page React Application. It sets up a comfortable environment for building react...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here