By d.code


2017-01-20 01:11:50 8 Comments

Redux docs for bindActionCreators states that:

The only use case for bindActionCreators is when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to pass dispatch or the Redux store to it.

What would be an example where bindActionCreators would be used/needed?

Which kind of component would not be aware of Redux?

What are the advantages/disadvantages of both options?

//actionCreator
import * as actionCreators from './actionCreators'

function mapStateToProps(state) {
  return {
    posts: state.posts,
    comments: state.comments
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch)
}

vs

function mapStateToProps(state) {
  return {
    posts: state.posts,
    comments: state.comments
  }
}

function mapDispatchToProps(dispatch) {
  return {
    someCallback: (postId, index) => {
      dispatch({
        type: 'REMOVE_COMMENT',
        postId,
        index
      })
    }
  }
}

5 comments

@Bhojendra Rauniyar 2018-08-31 19:11:23

The docs statement is very clear:

The only use case for bindActionCreators is when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to pass dispatch or the Redux store to it.

This is clearly a use case that may arise in the following and only one condition:

Lets say, we have component A and B:

// A use connect and updates the redux store
const A = props => {}
export default connect()(A)

// B doesn't use connect therefore it does not know about the redux store.
const B = props => {}
export default B

Inject to react-redux: (A)

const boundActionCreators = bindActionCreators(SomeActionCreator, dispatch)
// myActionCreatorMethod,
// myActionCreatorMethod2,
// myActionCreatorMethod3,

// when we want to dispatch
const action = SomeActionCreator.myActionCreatorMethod('My updates')
dispatch(action)

Injected by react-redux: (B)

const { myActionCreatorMethod } = props
<B myActionCreatorMethod={myActionCreatorMethod} {...boundActionCreators} />

Noticed of the following?

  • We updated the redux store through the component A whilst we were unknown of redux store in component B.

  • We're not updating in component A. To know what exactly I mean, you may explore this post. I hope you'll have an idea.

@vsync 2018-10-14 13:28:35

I didn't understand anything

@Diana Suvorova 2018-02-05 19:23:44

I don't think that the most popular answer, actually addresses the question.

All of the examples below essentially do the same thing and follow the no "pre-binding" concept.

// option 1
const mapDispatchToProps = (dispatch) => ({
  action: () => dispatch(action())
})


// option 2
const mapDispatchToProps = (dispatch) => ({
  action: bindActionCreators(action, dispatch)
})


// option 3
const mapDispatchToProps = {
  action: action
}

Option #3 is just a shorthand for option #1 , so the real question why one would use option #1 vs option #2. I've seen both of them used in react-redux codebase, and I find it is rather confusing.

I think the confusion comes from the fact that all of the examples in react-redux doc uses bindActionCreators while the doc for bindActionCreators (as quoted in the question itself) says to not use it with react-redux.

I guess the answer is consistency in the codebase, but I personally prefer explicitly wrapping actions in dispatch whenever needed.

@ogostos 2018-10-15 10:17:31

how is option #3 a shorthand for option #1?

@Artem Bernatskyi 2018-10-17 21:54:06

@ogostos 2018-10-18 11:56:20

@ArtemBernatskyi thanks. So, turns out there are 3 cases for mapDispatchToProps: function, object and missing. How to handle each case is defined here

@knee-cola 2017-10-27 14:33:15

I'll try to answer the original questions ...

Smart & Dumb components

In your first question you basically ask why bindActionCreators is needed in the first place, and what kind of components should not be aware of Redux.

In short the idea here is that components should be split into smart (container) and dumb (presentational) components. Dumb components work on the need-to-know basis. Their soul job is to render given data to HTML and nothing more. They shouldn't be aware of inner workings of the application. They can be seen as the skin deep front layer of your application.

On the other hand smart components are kind of a glue, which prepares data for the dumb components and preferably does no HTML rendering.

This kind of architecture promotes loose coupling between UI layer and the data layer underneath. This in turns allows easy replacement of any of the two layers with something else (i.e. a new design of the UI), which will not break the other layer.

To answer your question: dumb components shouldn't be aware of Redux (or any unnecessary implementation detail of the data-layer for that matter) because we might want to replace it with something else in the future.

You can find more about this concept in the Redux manual and in greater depth in article Presentational and Container Components by Dan Abramov.

Which example is better

The second question was about advantages/disadvantages of the given examples.

In the first example the action creators are defined in a separate actionCreators file/module, which means they can be reused elsewhere. It's pretty much the standard way of defining actions. I don't really see any disadvantages in this.

The second example defines action creators inline, which has multiple disadvantages:

  • action creators can't be re-used (obviously)
  • the thing is more verbose, which translates to less readable
  • action types are hard coded - it's preferably to define them as consts separately, so that they can be referenced in reducers - that would reduce a chance for typing mistakes
  • defining action creators inline is against recommended/expected way of using them - which will make your code a bit less readable for the community, in case you plan to share your code

The second example has one advantage over the first one - it's faster to write! So if you don't have greater plans for your code, it might be just fine.

I hope I managed to clarify things a bit ...

@Charlie 木匠 2017-09-26 19:17:59

More complete example, pass an object full of action creators to connect:

import * as ProductActions from './ProductActions';

// component part
export function Product({ name, description }) {
    return <div>
        <button onClick={this.props.addProduct}>Add a product</button>
    </div>
}

// container part
function mapStateToProps(state) {
    return {...state};
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        ...ProductActions,
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Product);

@markerikson 2017-01-20 18:15:28

99% of the time, it's used with the React-Redux connect() function, as part of the mapDispatchToProps parameter. It can be used explicitly inside the mapDispatch function you provide, or automatically if you use the object shorthand syntax and pass an object full of action creators to connect.

The idea is that by pre-binding the action creators, the component you pass to connect() technically "doesn't know" that it's connected - it just knows that it needs to run this.props.someCallback(). On the other hand, if you didn't bind action creators, and called this.props.dispatch(someActionCreator()), now the component "knows" that it's connected because it's expecting props.dispatch to exist.

I wrote some thoughts on this topic in my blog post Idiomatic Redux: Why use action creators?.

Related Questions

Sponsored Content

7 Answered Questions

[SOLVED] Why do we need middleware for async flow in Redux?

8 Answered Questions

[SOLVED] Why use Redux over Facebook Flux?

2 Answered Questions

5 Answered Questions

[SOLVED] How to pass actions down to the components in redux

3 Answered Questions

[SOLVED] What are differences between redux, react-redux, redux-thunk?

5 Answered Questions

[SOLVED] What is mapDispatchToProps?

  • 2016-09-09 20:26:43
  • Code Whisperer
  • 156952 View
  • 252 Score
  • 5 Answer
  • Tags:   reactjs redux

1 Answered Questions

1 Answered Questions

[SOLVED] redux pre-binding through bindActionCreators, an anti-pattern?

1 Answered Questions

2 Answered Questions

[SOLVED] React Redux connect() with Redux thunk

Sponsored Content