Why to use React Context?
React Context solves two major problems that using state and props can’t be solved.
1. Helps in avoiding prop drilling
Suppose we have to pass data from the parent component to its grandchild, what do we generally do? we pass data as props from parent to its child and then from child, we pass data as props to its grandchild. In this whole scenario child does not need that data but still, it is becoming a bridge to connect parent and grandchild.
This passing of props from higher-level components to deeply nested components using intermediate components is basically prop drilling. Prop drilling can cause performance issues because when the prop changes, intermediate components will also re-render unnecessarily and prop drilling also makes the code less maintainable.
2. Helps in Lifting the state up
Lifting the state up means if the sibling components want to share data using a common state then we have to declare that state in the parent component of all the siblings, as there is no other way to connect siblings. Since we are lifting the state from a lower level to a higher level, we call this lifting the state up.
Parent
/ \
Child1 Child2 - Siblings
React Context works as a centralized store from where any component can access the state they want. That means we don’t need to pass props using prop drilling. This is how React Context helps in avoiding props drilling, and make code more maintainable and also prevents unnecessary re-renders caused by prop drilling.
What is the use of React Context in React-Redux?
React Context is a feature that React provides us to manage states required in multiple components. Redux is also a state management library and solves the same problem that React Context does but in a different way. In this article, we will see in detail what is react context, why and how to use it, how it is related to and different from react-redux, and then at last we’ll see which one to use and when.
Table of Content
- What is React Context?
- Why to use React Context?
- How to set up React Context?
- How React Context is related to React-Redux?
- What to use and When?
Contact Us