Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why redux suggests to only connect to top level components?

Tags:

I'm new to redux and react-redux, in the mean time I am trying to make a redux app.

I don't understand the statement on redux document:

Then, we wrap the components we want to connect to Redux with the connect() function from react-redux. Try to only do this for a top-level component, or route handlers. While technically you can connect() any component in your app to Redux store, avoid doing this too deeply, because it will make the data flow harder to trace.

Isn't it easier to connect to all components and when state is updated, every component can get the new state tree?

Why dumb components and high level containers?

Thanks.

like image 826
Kevin He Avatar asked Dec 11 '15 00:12

Kevin He


People also ask

Can I pass multiple components within connect Redux?

Since you can have only one default export, you'd have to use named export in this case or split up those two components in two files.

Why we need connect in Redux?

The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.

Why would you not want to use Redux?

Cases when not to use Redux Using Redux in simple and small apps may add unjustified complexity to the app architecture, lead to wasteful memory usage, and require adding a caching solution to backup the application state.


1 Answers

As mentioned, Abramov (Redux author) has walked-back his advice re: connect()ed components. He articulates a nice rule of thumb in this Reddit post on the topic:

I do it this way:

  1. Start by using one container and several presentational components

  2. As presentational component tree grows, “middle” components start to pass too many props down

  3. At this point, I wrap some leaf components into containers so that “middle” components don’t need to accept and pass down props that are completely unrelated to them

  4. Repeat

If you watch the last ten videos from my course on Egghead, this is exactly the approach I demonstrate: https://egghead.io/series/getting-started-with-redux

From my reading, the initial advice on connect() had nothing to do w/ performance and everything to do with modular components & ease-of-reasoning about data flow in larger apps.

In fact, more connect()ed components might be a performance advantage vs. the 1-container-to-rule-them-all top-heavy pattern. Abramov once more:

Both approaches are fine, and having nested connect() components is actually going to give you more performance. The downside is they're slightly more coupled to the application and slightly harder to test, but that may not be a big issue.

like image 98
Brandon Avatar answered Sep 19 '22 13:09

Brandon