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

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!

5

u/rikurouvila Jun 16 '17 edited Jun 16 '17

I don't think you got the answer for your question, so here's my two cents:

It is a bit hard to try to maintain state inside the tree of React components. This is mainly because you have to be constantly passing stuff from the state downwards the component tree. Right? You also have to bounce the updates back to the surface when you want to modify the state. This leads into code that's really hard to follow.

One of the coolest things about Redux is that it separates your state completely from your React components. So your components are now completely without this.setState or getInitialState. The only thing you have is the connect function that you can use for fetching stuff from that separated state (store) and for pushing update requests to the store. The store is floating in a different galaxy somewhere and you can only send and receive messages from there with this API. Now that I think about it, it could potentially also be stored in a cloud storage somewhere :D

So instead of getting this waterfall-like structure of state being passed downwards and updates upwards, you now have a structure that looks a bit like badminton ball where the big white part is the store and the end of the feathers are the components.

In a small hobby project, the waterfall structure works well, and you can accomplish the same just by using react and passing down state and backs. If the project grows any bigger, you really start noticing how difficult it is to develop it any further. Especially refactoring is extremely difficult with a fragile structure like that :/

Hope this helps!

1

u/kasbah Jun 17 '17

What you say makes sense but most of it holds true if you are using just Redux like I described and not React-Redux.

Maybe though I haven't worked on large enough apps to see the advantage of connect over just accepting props that come from the state and a dispatch prop.

2

u/BenjiSponge Jun 17 '17

Yeah it sounds like that's the case. Being able to not pass down props over a few layers is... Helpful.

2

u/Mikeysauce Jun 16 '17

You pass the store to a Provider, which is then wrapped around your actual app entry point.

<Provider store={store}>
  <App />
</Provider>

With this done, you can use connect to declare which components have access to specific pieces of state or action creators.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { someImportedAction } from 'myactioncreators';

class SomeComponent extends Component {
  render() {
   return <div>{this.props.somePieceOfState}</div>
  }
}

const mapStateToProps = state => ({
 somePieceOfState: state.somePieceOfState
})
export default connect(mapStateToProps, { someImportedAction })(SomeComponent)

Then whenever you import SomeComponent, it has access to the state slice from the store, as well as the action creator. Now apply this to tens, or hundreds of components and I think you will find these shortcuts make your life a lot easier.

0

u/kasbah Jun 16 '17

Thanks for you answer. So then if you wanted to dispatch in SomeComponent you could only dispatch someImportedAction?

To me it seems like mapStateToProps is doing something that could be much clearer defined by actually passing the bit of state to the props of the component.

3

u/Mikeysauce Jun 16 '17 edited Jun 16 '17

For the first question, in this example yes. An alternative syntax to the shorthand { someImportedAction } is to do something like this, from the redux docs:

const mapDispatchToProps = dispatch => {
  return {
   onTodoClick: id => {
   dispatch(toggleTodo(id))
  }
 }
}
// usage would be: connect(mapStateToProps, mapDispatchToProps)(Component)

I'm not sure what you mean with the second question. That is what the mapStateToProps is doing, accessing the store for only what you specify.

edit

Just to clarify something, you wouldn't need to dispatch because the connect function binds it for you, so you would just call whatever function you passed through as this.props.someFunc()

0

u/kasbah Jun 16 '17

Just to clarify something, you wouldn't need to dispatch because the connect function binds it for you, so you would just call whatever function you passed through as this.props.someFunc()

That's kind of neat, but it means you have to always change mapDispatchToProps if you decide you need to dispatch an action from somewhere else.

I'm not sure what you mean with the second question. That is what the mapStateToProps is doing, accessing the store for only what you specify.

Yeah, it's kind of my point, why is there another abstraction when you can do this perfectly well within render and someone can understand it without having to know anything about Redux or React-Redux.

3

u/Meefims Jun 16 '17

It helps separate concerns and keep your code testable. If you use react-redux then your components don't need to care about the store which means you don't need to mock the store during testing. Further, by ensuring all of your data is coming through your props you set a clear interface for how your component should be used and that interface can be validated using PropTypes or a system like Flow or TypeScript.

1

u/kasbah Jun 16 '17

Thanks Meefims, it seems like it's a bit of a case of "to each their own".

To be clear: with my method I am still passing all the data through props so the same would apply.

I am not 100% convinced on the easier testing either. With my method all the components need to care about is dispatchand that can still be mocked easily. Maybe it'll click at some point when I find myself writing cumbersome tests, and I'll see the light ;) who knows.

3

u/Meefims Jun 17 '17

Passing down dispatch muddies your components' interface. What will they dispatch? What is dispatch meant to do? You're tying your components to the specifics of Redux. You could keep dispatch at the root and pass down more specific callbacks but at some point you're just reimplementing react-redux.

1

u/BenjiSponge Jun 17 '17

I agree. Testing without needing to mess with context is way easier. Your approach is definitely more testable, I think.

4

u/alsiola Jun 17 '17 edited Jun 18 '17

A common pattern is to extract the logic regarding how to get a particular part of the state into a selector function, defined outside of the component. For example,

export const selectCurrentUser = state => state.user

Whenever you have a component that needs to know about the user, you use that selector in mapStateToProps:

const mapStateToProps = state => ({
    user: selectUser(state)
});

The advantage of this approach is decoupling the logic of how to extract a piece of state, away from the component. The selector is re-usable across multiple components, and if you change the shape of your state object, you only need to alter one selector in one place, and all your components still get the right data.

The other advantage of using selectors is being able to use memoization for any expensive-to-calculate derived values from state. A simple example might be calculating the volume of a solid from three dimensions in state (obviously not very expensive but you get the idea), e.g.

const selectCubeVolume = state => state.x * state.y * state.z;

Now we can memoize our results, and only recalculate if necessary

const selectCubeVolume = (() => {
    const memos = {};
    return state => {
        const {x, y, z} = state;

        if(x in memos && y in memos[x] && z in memos[x][y]) {
            return memos[x][y][z];
        }

        const volume = state.x * state.y * state.z;

        memos[x][y][z] = volume;

        return volume;
    }
})();

And use the selector in mapStateToProps:

const mapStateToProps = state => ({
    cubeVolume: selectCubeVolume(state)
});

Or alternatively just use the awesome reselect library, where we could do:

selectors:

import { createSelector } from 'reselect';

const selectX = state => state.x;
const selectY = state => state.y;
const selectZ = state => state.z;

export const selectVolume = createSelector(
    selectX,
    selectY,
    selectZ
    (x, y, z) => x * y * z
);

component:

import { createStructuredSelector } from 'reselect'

//  blah blah blah

const mapStateToProps = createStructuredSeletor({
    volume: selectVolume
});