petithomme
petithomme

Reputation: 549

React redux application connect() function

Not sure if it's the right website to ask this question but I I'll give it a go.

When building a web app with React and Redux, how should one use the connect() function? Is the goal to only have one container connected to the store at the top that passes the props to it's children or to have multiple containers connected to the store that passes down props to their children? I've built a small web app that only has one container that is connected to the store and therefore it passes all its props down.

I was wondering what solution was best and if it's the multiple containers connected one, how does one build his app's architecture that way?

Thank you.

Upvotes: 1

Views: 312

Answers (1)

markerikson
markerikson

Reputation: 67449

Quoting the Redux FAQ at http://redux.js.org/docs/faq/ReactRedux.html#react-multiple-components :

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.

The current suggested best practice is to categorize your components as “presentational” or “container” components, and extract a connected container component wherever it makes sense:

Emphasizing “one container component at the top” in Redux examples was a mistake. Don't take this as a maxim. Try to keep your presentation components separate. Create container components by connecting them when it's convenient. Whenever you feel like you're duplicating code in parent components to provide data for same kinds of children, time to extract a container. Generally as soon as you feel a parent knows too much about “personal” data or actions of its children, time to extract a container.

In fact, benchmarks have shown that more connected components generally leads to better performance than fewer connected components.

In general, try to find a balance between understandable data flow and areas of responsibility with your components.

Upvotes: 2

Related Questions