Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should connect components to redux in react?

For example, i have a structure of components like this:

<Parent>
      <Child_1>
            <InnerChild_1 />
      </Chidl_1>
      <Child_2>
            <InnerChild_2 />
      </Chidl_2>
</Parent>

Component <Parent> connected to redux. What a better way to update <InnerChild_1 /> with application state, send this data from <Parent> with props or connect <InnerChild_1 /> to redux ? If connect, should i connect all my components, that's using state, to redux?

like image 814
Andrew Avatar asked Oct 26 '25 08:10

Andrew


1 Answers

Despite every other answer stating that you should connect your top level, that's indeed an old recommendation that is only useful for very simple applications.

Use connect wherever you need to keep a component synchronized with the Redux store. In your example, if <Parent /> is not using any state and its role is merely compositional, I wouldn't connect that one. I would keep Parent a standard React component, and connect the child items individually.

For big lists or complex data structures with nested entitites, that's the way to go.

If you choose the other way, and connect at your top-most component, then any state change will cause a full re-render of your component tree, with no automatic optimization. Because connected components will implement shouldComponentUpdate for you, you'll normally get much better performance connecting multiple items to the store instead of connecting a "list" parent and re-render every item on every change.

See the React-Redux FAQ in the Redux docs: http://redux.js.org/docs/faq/ReactRedux.html#react-multiple-components

Specifically:

Early Redux documentation advised that you should only have a few connected components near the top of your component tree. However, time and experience has shown that that generally requires a few components to know too much about the data requirements of all their descendants, and forces them to pass down a confusing number of props.

like image 145
CharlieBrown Avatar answered Oct 28 '25 22:10

CharlieBrown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!