Avoid Prop Drilling with React Context
This blog will teach you how to tidy up your React code, and avoid prop drilling using a helpful React API called Context
.
What is prop drilling?
Prop drilling is the process in a React app where props are passed from one part of a tree to another by going through other parts that do not need the data, but only help in passing it through the tree.
As an example, suppose you have an application that has two themes: light
mode and dark
mode. Then suppose you have the following Component tree in your app:
If you wanted the Button
component to know if we are in light
or dark
mode, often you will see a theme
prop being passed from App -> Toolbar -> Button
. Your code may look something like this:
This code is an example of prop drilling, as we need to explicitly pass the theme
prop through every part of the component tree, even parts that…