Reputation: 791
I am working my way through the redux tutorial here. I have some experience with "traditional Flux" so the first codeblock looks familiar to me, but I am confused by the second statement.
In traditional Flux, action creators often trigger a dispatch when invoked, like so:
function addTodoWithDispatch(text) { const action = { type: ADD_TODO, text } dispatch(action) }
In Redux this is not the case. Instead, to actually initiate a dispatch, pass the result to the dispatch() function:
dispatch(addTodo(text)) dispatch(completeTodo(index))
If my action creator is this:
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
dispatch(addTodo(text))
Isn't that functionally equivalent to the first code example? Why does redux require the second way to actually dispatch?
Upvotes: 1
Views: 191
Reputation: 73918
Action Creators are used in Redux for adding extra layers of indirection and abstraction.
There are several reasons to use action creators rather than putting all your logic directly:
Encapsulation: Consistently using action creators means that a component doesn't have to know any of the details of creating and dispatching the action.
Abstraction: Put the logic for creating that action in one place.
Brevity: There could be some larger logic that goes into preparing the action object, rather than just immediately returning it.
Testability: It is easy to write tests for the component that pass in a mock version of the function instead. It also enables reusing the component in another situation.
Useful resources:
http://redux.js.org/docs/basics/Actions.html#action-creators
http://blog.isquaredsoftware.com/2016/10/idiomatic-redux-why-use-action-creators/
Upvotes: 2