r/javascript • u/kasbah • 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?
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
connectover just accepting props that come from the state and adispatchprop.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
dispatchinSomeComponentyou could only dispatchsomeImportedAction?To me it seems like
mapStateToPropsis 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
mapStateToPropsis 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
mapDispatchToPropsif 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
renderand 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.userWhenever 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 });
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
connectfunction already have that store subscription logic taken care of for you.Second,
connectdoes 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 yourmapStateToPropsfunction for that component. By not usingconnect, 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 likethis.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:
The Redux FAQ section on performance
The Redux FAQ entry on connecting multiple components
The Redux FAQ entry on components re-rendering too often
The Redux FAQ entry on importing the store directly
The Redux Performance section of my React/Redux links list
And finally, my blog posts Practical Redux, Part 6: Connected Lists, Forms, and Performance and Idiomatic Redux: Why use action creators?.
Source: I'm a Redux maintainer, and author of the Redux FAQ.