React Context API For Dummies
Introduction
The techy definition of React Context API(RCA) is a way to create a global variable to be passed around in the app. What does this really mean though? Think of RCA as the water cycle. In the figure above, water cannot move from one lake to the next without first evaporating. The water vapor must then condense into clouds and be pushed by the wind. Finally, the cloud rains down on the second lake to complete the cycle.
As you can tell, I understand concepts best with analogies and visual aids. The water is equivalent to data that needs to be passed around in an app. For example, on Amazon when someone clicks the “add to basket” button, the product chosen needs to “evaporate” or be stored in a “cloud” or data layer. The “wind” or user then navigates to the “second lake” or checkout page where the information is “precipitated” or displayed.
What is Prop Drilling?
Imagine if in our analogy above, the water in the first lake had to move back upstream to its original source to then be evaporated. This would be very inefficient and a waste of time. This is what we call prop drilling. Very often, if we aren’t using RCA or something similar, we need to pass props or data down a component chain in order for it to reach the designated component. This can cause the page to have longer loading times and data can get lost.
What does the code look like?
Lets revisit the Amazon example from above.
This is the home page with the product selection.
When the user clicks on the “Add to Basket” button, the data is sent to Product.js .
Here the product information is pulled in with the code in the return function. Using useStateValue, dispatch, and addToBasket, the data can now be sent to the data layer to be stored. Dispatch can be used to both pull and add to the data layer.
Next we will take a look at the data layer which is located in a file called reducer.js .
Notice that both Product.js and reducer.js have a function called “ADD_TO_BASKET”. This connects the home page with the data layer and allows the product selected to be stored within an array called basket.
Finally, CheckoutProduct.js was created to display the product within the checkout page. It also contains useStateValue and dispatch to allow the data to be retrieved from the data layer.
Conclusion
Hopefully the analogy provided in this article can help to clarify what React Context API can do. It is a simple but powerful tool that allows the developer to create more efficient apps.