echen
echen

Reputation: 2072

redux pre-binding through bindActionCreators, an anti-pattern?

Throughout my redux App, I frequently finding myself using the following pattern

// declare an action creator in a centralized / state management related location in the App (i.e. not the components/containers)
const myActionCreator1 = () => (dispatch) => { ... }
const myActionCreator2 = createAction(ACTION_2)
// then later in a mapDispatchToProps of a Container component
function mapDispatchToProps(dispatch) {
  bindActionCreators({myActionCreator1, myActionCreator2}, dispatch);
}

Is these cases, is it an anti-pattern to pre-bind the action creators? given that there is only 1 dispatcher in redux working against 1 store?

i.e.

// actionCreators.ts
export const myActionCreators = {
  myActionCreator: bindActionCreators(..., dispatch)
}

If this is pattern has no downside that would be good news for conciseness ....

Clarification

the conciseness benefit will only be apparent when multiple components re-use the same action creator. As these components will no longer require a mapDispatchToProps for straight-forward cases like the examples above

Upvotes: 0

Views: 596

Answers (1)

markerikson
markerikson

Reputation: 67469

The connect function supports an "object shorthand" syntax for the second argument. Instead of creating a mapDispatchToProps function that receives dispatch (and probably uses bindActionCreators inside), you can just pass an object full of action creators directly to connect:

const actionCreators = {
    addTodo,
    toggleTodo
};

export default connect(null, actionCreators)(MyComponent);

That object full of action creators will be automatically run through bindActionCreators, and calling this.props.addTodo("Buy Milk") will dispatch the action creator appropriately.

I discussed some of the advantages of this approach in my blog post Idiomatic Redux: Why use action creators?.

Upvotes: 1

Related Questions