Using the Context API to resolve prop drilling
The concept behind using the Context API to address prop drilling is to create a shared container for all sub-components under a common parent. This eliminates the need for explicitly passing down props from parent to child. Sub-components can directly access the shared context whenever necessary. Another advantage of using the Context API is that it triggers automatic re-rendering of components whenever the data within the context changes.
Returning to our searchable list example, which has already got the props drilling issue, onItemClicked
in the List
component isn’t necessary as List
doesn’t use the prop. This scenario involves just one layer and one prop. Now, envision a situation where we need to insert additional elements between the List
and ListItem
components; we would have to pass the onItemClicked
prop down to where it’s utilized. The complexity is amplified if we have multiple props to relay.
The...