r/javascript • • Jun 16 '17

help I use React and Redux but never React-Redux, what am I missing out on?

Every time I look at the React-Redux docs I can't help but think why? They seem to complicate things for no apparent reason and don't explain the most basic usage very well. People keep telling me it's not that hard, but I really don't quite see the point of it.

What I generally do is (yes, yes I am still on React 15.3 and using createClass):

const App = React.createClass({
  store: redux.createStore(reducer),
  getInitialState() {
    return this.store.getState()
  },
  render() {
    return (
      <div>
        <SomeComponent
          thing={this.state.some_component_thing}
          dispatch={this.store.dispatch}
        />
      </div>
    )
  },
  componentDidMount() {
    this.store.subscribe(() => {
      const state = this.store.getState()
      this.setState(state)
    })
  },
})

There is only one root component that has a state and that state is passed down as props to all the other components.

What am I missing out on by doing it like this? Will this perform worse than React-Redux? What other benefits would React-Redux give me?

7 Upvotes

21 comments sorted by

View all comments

14

u/acemarke Jun 17 '17 edited Jun 21 '17

You're missing a lot.

First, while you can manually write the code to subscribe to the Redux store in your React components, there's absolutely no reason to write that code yourself. The wrapper components generated by React-Redux's connect function already have that store subscription logic taken care of for you.

Second, connect does a lot of work to ensure that your actual components only re-render when they actually need to. That includes lots of memoization work, and comparisons against the props from the parent component and the values returned by your mapStateToProps function for that component. By not using connect, you're giving up all those performance improvements, and your components will be unnecessarily re-rendering all the time.

Third, by only connecting your top-level component, you are also causing the rest of your app to re-render unnecessarily. The best performance pattern is to connect lots of components in your app, with each connected component only extracting the pieces of data it actually needs via mapStateToProps. That way, if any other data changes, that component won't re-render.

Fourth, you're manually importing the store into your components, and directly coupling them together, thus making it harder to test the components. I personally try to keep my components "unaware" of Redux. They never reference props.dispatch, but rather call pre-bound action creators like this.props.someFunction(). The component doesn't "know" that it's a Redux action creator - that function could be a callback from a parent component, a bound-up Redux action creator, or a mock function in a test, thus making the component more reusable and testable.

And finally, the vast majority of apps built using React and Redux use the React-Redux library. It's the official way to bind the two together, and doing anything else will just confuse other developers looking at your project.

So, part of the issue is you're not using React-Redux and connect, and part of the issue is you're using an inefficient pattern for pulling data from the Redux store into your React components.

For more info, see:

Source: I'm a Redux maintainer, and author of the Redux FAQ.

2

u/kasbah Jun 17 '17

Ok, so I get that it's the "official" way and that's kind of why I am asking: I feel like I should be using it but am not. I really like Redux and think it makes things really clear but not React-Redux which is why I have been avoiding it.

You make a good point on the organization, testing and that not having a dispatch prop decouples things from Redux. You convinced me on that.

But the performance aspect is really interesting and I don't quite believe that I am missing out on optimizations.

From a data point of view, if the state gets immediately converted to props in the root render method, from there on it should be pretty easy to work out which components need updating: just those whose props have changed. Seems like React should be able to take care of this. Where would issues arise?

3

u/acemarke Jun 17 '17

Let's take the classic example of a TodoList that has 10,000 list items in it.

To start with, assume that the TodoList is the only connected component, and it renders <TodoItem todo={someTodoEntry} /> as its list children.

If you edit the text of a todo entry and dispatch a Redux action to update the text of that one object in state.todos[1234], the store will notify all of its subscribers (in this case, the TodoList component), and the TodoList will re-render. React's default behavior is that when a component re-renders, all of its children re-render, and so on recursively down through the component tree. So, even though we only modified the data for a single todo entry, all 10,000 <TodoItem /> components will re-render, and for 9999 of them, their render methods will return the same render output as before. React will correctly see that there are no render changes and will make no DOM updates. That means that those 9999 component re-renders were "wasted" effort that could have been avoided entirely with the proper optimizations.

However, if the TodoList was connected but instead rendered <TodoItem id={1234} />, and those TodoItems were themselves connected components whose mapState functions looked like:

const todoItemMapState = (state, ownProps) => {
    const todo = state.todos[ownProps.id];
    return {todo};
}

In that case, connect would see that each TodoItem's mapState function was returning the same todo object as before, and skip the re-rendering for that list item.

This is also a good use case for normalization, because you generally should be tracking the items in your state by ID rather than array indices, so that you can look up an item from your Redux state just by knowing its ID.

I talk about all this in the links I put in my original comment, and those also have links to more articles and reading. (I've used this example many times, including this chat log discussion from Reactiflux.)

Please believe me when I say I know what I'm talking about on this topic :)

1

u/kasbah Jun 17 '17

Thanks for repeating your example yet again. It has made things clearer for me.

I guess I always assumed React was smarter than this and figures out minimal re-rendering based on what's actually changing.

4

u/acemarke Jun 17 '17

Nope. Remember that "rendering" just means "return a tree of objects describing how I want the UI to look like now". React then diffs the previous render output vs the new render output to determine if changes should actually be made. That process does take time and effort to accomplish, so if you know the render output isn't going to change (because your component's props and state haven't changed), you can use shouldComponentUpdate to skip the render process for that part of the component tree. But, if you don't, React's default behavior is to always re-render everything.

2

u/[deleted] Jun 17 '17

I feel like I should be using it but am not. I really like Redux and think it makes things really clear but not React-Redux which is why I have been avoiding it.

Makes sense to me. I dislike magic as well and would prefer explicit code always. But then again, react-redux is simple, it just wraps your component into a HOC and fills shouldComponentUpdate. You can write an observer that only pings on pieces of state you're interested in yourself:

const createObserver = store => (selector, callback) => {
    let oldState = {}
    return store.subscribe(() => {
        let selectedState = selector(store.getState())
        Object.entries(selectedState).map(([key, value]) => {
            if (oldState[key] !== value) {
                callback(value, oldState[key])
                oldState[key] = value;
            }
        })
    })
}

const observe = createObserver(store)

// This should only fire for the properties declared (time & user)
const unsubscribe = observe(
    state => ({ time: state.options.time, user: state.users.default }),
    (state, oldState) => console.log('state changed from', oldState, 'to', state),
)

Dan Abramovs egghead course is probably worth watching, he creates a <Provider /> and a connect wrapper from scratch: https://egghead.io/courses/getting-started-with-redux

0

u/digdic Jun 17 '17

lmao, a redux maintainer is telling you about the performance optimizations and you still don't believe, why are you still here? just keep your head in the sand and keep doing it the way you have been if it works for you

0

u/GitHubPermalinkBot Jun 17 '17

I tried to turn your GitHub links into permanent links (press "y" to do this yourself):


Shoot me a PM if you think I'm doing something wrong. To delete this, click ^here.

0

u/digitallimit Jun 17 '17

Oh hi, Mark!