Add `state` as the third parameter to `mapDispatchToProps`
See original GitHub issueSo that I could do this:
var ToggleFollowButton = ({toggleFollow}) => <button onClick={toggleFollow}>Toggle</button>;
ToggleFollowButton = connect(null, (dispatch, ownProps, state) => {
const toggle = state.postsFollowing[ownProps.id]
? unfollowPostActionCreator
: followPostActionCreator;
return {
toggleFollow: () => dispatch(toggle(ownProps.id)))
};
})(ToggleFollowButton)
Now I’m fully aware that I can do this in the component code by passing the “follow state” and both action creators to it, but when using function components this would be more performant way to do this. In normal class based component I can do this only once as a method but with a function component I lose some performance because the toggle function is recreated on every render. Also when using react/jsx-no-bind
eslint rule it’s hard to avoid the warning.
Another point is that if the toggle function is recreated on every render it can interfere with PureRenderMixin optimized components further down in the component tree.
Another option would be to add dispatch
to mapStateToProps
as the third argument. Which actually could be prettier because then the object shorthand for mapDispatchToProps
would be still available.
EDIT: Also it would be easier to implement because the reinvoke semantics of mapDispatchToProps
would not change. So I’ll actually propose this version 😃
I can also send a PR if we see this as something we want.
Issue Analytics
- State:
- Created 8 years ago
- Comments:18 (10 by maintainers)
Top GitHub Comments
Same example in a less terse way:
connect()
accepts a third argument calledmergeProps
precisely for this use case.Or, in a more readable way:
I think adding
getState()
tomapDispatchToProps
has the potential of being very confusing and people might start using it instead ofmapStateToProps
and wonder why it doesn’t redraw.