In the last lesson, we learned the concept of lifting state, where we moved a state to the nearest common parent and passed it down via props to share the state between components. However, passing props can become inconvenient, especially when the nearest common ancestor is far removed from the components that need data, and lifting the state that high can lead to a situation called prop drilling. Excessive prop drilling not only makes the code harder to manage but can also cause unwanted re-renders in components that receive props they don't actually use, potentially affecting the performance of the application. Let’s dive deeper and understand what prop drilling is, and look at a couple of common scenarios where it can become a problem.
What is Prop Drilling?
Prop drilling occurs when a parent component must send data to a nested child, and
each layer in between must receive and forward those props even if it doesn't use them.
Over time, these forwarded props accumulate, leading to code which is hard to read along with unnecessary re-renders in components that merely pass props along.
Let's take a scenario where we want to make some enhancements in a large component
to understand prop drilling. Consider the following component directory MyFeature
:
Initially, everything works fine, but then you decide to add an enhancement which requires an enableTracking flag that only SectionB uses. With plain props, you end up writing:
Each future enhancement similar to this, would involve adding more props, making the structure brittle.
Let's look at another scenario where prop drilling could occur.
Consider a multi-step form composed of FormContainer
, StepOne
, StepTwo
, and SubmitButton
.
The button needs to call an onSubmit
callback defined in FormContainer
.
Without context or hooks, you end up drilling this callback through each step component:
Even though StepOne
and StepTwo
have nothing to do with submission,
they still need an onSubmit
prop in their signatures.
In the next chapter, we'll explore different strategies through which we can avoid prop
drilling and keep your component tree clean and maintainable.