4 ms·
By default, `createAction` accepts a single argument, which it then includes as `action.payload.` This requires the least amount of code written to define the
by acemarke 7y ago
By default, `createAction` accepts a single argument, which it then includes as `action.payload.` This requires the least amount of code written to define the action creator, but requires the dispatching code (such as a click handler) to correctly format the payload contents. It aims for the 80% use case by default.
However, yes, there are many cases where you might want to accept multiple arguments for an action creator, do additional work to define the contents of the payload, or generate unique IDs as part of creating the action. That's why `createAction` also accepts a "prepare callback" as its second argument [0] [1].
`createSlice`'s primary benefit is to remove the need to write action types and action creators by hand. All you have to do is write your reducer functions, give them meaningful names, and you get the action generated creators for free (and the action types effectively become an invisible implementation detail).
We've always told folks that it is not required to have a 1:1 mapping between action types and reducers [2] and that many reducers can respond to a single action [3], but realistically speaking, most actions _are_ only handled by one reducer. Again, `createSlice` handles that 80% use case by generating actions that correspond to that given case reducer in the `reducers` argument, but also allow you to handle the "events" case by listening for other actions in the `extraReducers` argument. (And, the `reducers` argument allows defining "prepare callbacks" as well if desired [4]).
So, in both of these APIs, we solve the 80% use case by default, but allow handling the additional 20% if desired.
Most folks won't need to be calling `createAction` themselves given the existence of `createSlice`, but there's no reason to _not_ have it as part of the public API (especially since `createSlice` already uses it internally).
[0] https://redux-toolkit.js.org/api/createAction#using-prepare-callbacks-to-customize-action-contents https://redux-toolkit.js.org/api/createAction#using-prepare-...
[1] https://redux-toolkit.js.org/tutorials/intermediate-tutorial#implementing-todo-ids https://redux-toolkit.js.org/tutorials/intermediate-tutorial...
[2] https://redux.js.org/faq/actions#is-there-always-a-one-to-one-mapping-between-reducers-and-actions https://redux.js.org/faq/actions#is-there-always-a-one-to-on...
[3] https://redux.js.org/style-guide/style-guide#model-actions-as-events-not-setters https://redux.js.org/style-guide/style-guide#model-actions-a...
[4] https://redux-toolkit.js.org/api/createSlice#customizing-generated-action-creators https://redux-toolkit.js.org/api/createSlice#customizing-gen...