Reputation: 269
Is it bad practice / will it hurt performance if I pass props from a root component down to a child component 4-5 components down often?
Im thinking every component in the chain will have to rerender every time the props change, meaning bad performance, since its only a small child component inside the large component which actually needs to change.
If this is indeed the case, should I flatten my root component, or should I implement a custom 'shouldComponentUpdate', or something else?
Upvotes: 3
Views: 3565
Reputation: 1380
The need should be rare, but React's diff-ing algorithm will ensure nothing updates unless it is necessary. Performance should not suffer.
For instance, I usually start my apps with a container class which does a media query (using react-responsive
). Using this media query I pass either display="desktop"
or display="mobile"
as a prop down the next component. I usually pass this.props.display
all the way down my component tree and it is the deciding factor in how my CSS looks (either the desktop view or the mobile view). In this case, performance is actually enhanced!
Upvotes: 2
Reputation: 252
React won't re-render the DOM unless the tree actually requires an update/change therefore no rendering performance costs.
You can also use shouldComponentUpdate() to manage your updates to each component.
Facebook's React Reconciliation
Upvotes: 1
Reputation: 2311
Implementing shouldComponentUpdate
is very good practice to minimize re-rendering, especially if the components are kept simple and small to be able to define the shouldComponentUpdate
simple as well.
As an alternative, look into react-redux
or other state container to manage state easier without much hassle.
Upvotes: 3