Introduction
In a React application, data is passed from parent to child via props, but this can turn out to be cumbersome as the hierarchical tree structure increases or when the same props are being used by different component in the tree(a situation known as prop drilling).
To cope with this situation, there are two ways, one is using a third party library such as REDUX, and the other is react's own Context API.
Context provides a way to share attributes between components without having to explicitly pass them via props through every level of the tree.
When to use and when to avoid? Context is designed to share data that can be considered “global” for a hierarchical tree of React components. We should use context when we want to avoid passing of values down the hierarchical tree in the form of props and make use of the values wherever required. But we should avoid using context more often as it would make the component re-usability difficult. Rather than using context, we should make the component composition in such a way to promote better re-usability of props. Only use context when the attributes are global and required by most of the components in the hierarchical tree.
React Context API vs REDUX React Context API was introduced in React 16.3 with the sole idea of getting rid of prop drilling for globally required data values. Whereas, Redux is a third party library that provides various other features along with providing a global store. With Redux, we can monitor our state changes using redux devtools and also Redux has an inbuilt middleware that helps in managing the state with respect to asynchronous external API calls.
Components of Context API React’s Context API, generally consists of three building blocks:
A Context Object -- This can be considered as a JS object that is to be shared among various React components.
A Context Provider -- This can be considered as an element that makes the context object available to the entire react component tree. Context should be provided in a component that wraps all child components that eventually need access to the Context.
A Context Consumer -- This is the component that consumes the context object to use the property.
We will discuss about how to write and consume a context object in the next post.
Summary In this post, we have had a brief introduction to the context API, its differences from REDUX and its components.
Comments