React Prop drilling - Kent Dodds

A way of sharing state by passing state properties through components (which may not use the data themselves) to child components that need it. Kents article
Prop drilling is appropriate in some circumstances and is explicit (which makes it easier to debug). Lifting state up to the closest common component and then passing it down to child components is a pattern that works for many cases and we use all the time. 

But Prop drilling can come with problems
  • if the shape/name of data properties change
  • or child components change and no longer need the data
We've seen this happens quite often as apps scale up in size: "hmmm what children components use those props? I dunno" or "why is this child component broken?"

Kent says one way to avoid this is don't break out render into multiple components unnecessarily. Wait until you need to reuse. 
Now this is interesting to me. Many times we break up components into separate components for reasons other than just reuse and
 I don't believe reuse is the only criteria for breaking up a component. Long renders can be daunting to understand especially if they try to do too much e.g. I'd prefer to break list items plus handler into their own component rather than have the list view render and handle any list item actions. 
That's the kind of tradeoff we make all the time. 

Another way to avoid prop drilling is including more sub components in the parent rather than hiding all in the child. This is a useful technique though limited.

Shared global state has become a very common way to avoid prop drilling. It's what state management libraries like Redux provide. No prop drilling, voila! just put state on the shared state. We know there are problems with globals (including global state) and there's also the problem that it can be misused: everything gets put into Redux state, including state which should not be such as local state. Why not? it's easy to do so. But that does cause problems. 

Kent also mentioned not to use defaultProps for required fields (which could lead to hidden errors)

Here's the key takeaway for me: 
"Keep state as close to where it's relevant as possible. If only one section of your app needs some state, then manage that in the least common parent of those components rather than putting it at the highest level of the app."

Kent also talks about the React Context api, but that's grist for another post.

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more