Question

I understand React and Redux (at least think that I do). But the combination using the react-redux Binding package is a bit confusing to me.

https://github.com/reactjs/react-redux

The first thing that disturb me is the motivation to use connect. Why not just use store.subscribe(()=>{this.setState({})}) from the root Component?

Since the store is Global you can dispatch an action from any component and get the current state from any competent even deeply nested in hierarchy. So we do not need the react-redux for that although I can see how using react-redux can make it more strict and secure by binding only the properties that we need

This is the reason from the redux page to use the package: http://redux.js.org/docs/basics/UsageWithReact.html#presentational-and-container-components

React Redux makes many performance optimizations that are hard to do by hand

On the other hand React has Virtual Dom which: https://en.wikipedia.org/wiki/React_(JavaScript_library)#Virtual_DOM

React creates an in-memory data structure cache, computes the resulting differences, and then updates the browser's displayed DOM efficiently. This allows the programmer to write code as if the entire page is rendered on each change, while the React libraries only render sub components that actually change.

So it seems to me that the Virtual Dom and react-redux may do the same stuff. This violates the Single responsibility principle. Why do we need the extra complexity?

Can you clear this issue for me?

Was it helpful?

Solution

react-redux at the end provides a convenient way of accessing the store from any component (actually, as the documentation says, only container components should connect to the store). This means that any component that wants to get data can do it without relying on a parent component feeding it with props.

The alternative that you suggest ("Why not just use store.subscribe(()=>{ this.setState({}) }) from the root Component?") breaks down if you have a deep hierarchy of components. In that case, the root component gets the data, and has to pass it through a chain of children. In that case, you don't gain much over just using the normal setState.

Also with connect you can select which parts of the state you are accessing to, making it clearer what data each component uses.

In the end, redux is not needed for every React app, that depends on your use case. But if you are using React and Redux, that library makes combining them easier than just doing it yourself.

Licensed under: CC-BY-SA with attribution
scroll top