Standalone actions
A cross-slice or application-wide event needs a single reusable creator.
Redux Toolkit · Function
createAction combines an action type and creator into one helper. It returns a callable action creator whose argument normally becomes payload, with an optional prepare callback for custom action construction.
createAction combines an action-type declaration with its action-creator function. It returns a callable creator that accepts one payload argument by default, or uses an optional prepare callback to construct the payload and related action fields.
createAction(type, prepareAction?)| Name | Type | Description |
|---|---|---|
type | string | The string identifying the Redux action type. |
prepareAction | function | Optional callback used to construct the payload value and prepared action contents. |
An action creator for the supplied type; invoking it creates an action, with the argument normally assigned to payload.
import { createAction } from '@reduxjs/toolkit'
export const todoAdded = createAction<{ id: number; text: string }>('todos/todoAdded')
const action = todoAdded({ id: 1, text: 'Learn Redux Toolkit' })
console.log(action)
// { type: 'todos/todoAdded', payload: { id: 1, text: 'Learn Redux Toolkit' } }Creates a typed action creator and invokes it with the payload required by the action.
A cross-slice or application-wide event needs a single reusable creator.
Callers need to pass convenient inputs that must be converted into a payload.
An action is not owned by a particular slice reducer.
createAction return?createAction takes an action type and returns an action creator for that type. Calling the creator produces an action whose type is the supplied string and whose argument is normally assigned to payload.
Follow-up: When would a prepare callback be useful? It is useful when callers provide convenient inputs that must be transformed into the final payload, or when the action should include additional prepared metadata.
createAction?The standard signature is createAction(type, prepareAction?). The first parameter identifies the action type, while the optional second parameter prepares the payload and other action properties.
Follow-up: How does the default behavior differ from prepared actions? By default, the single call argument becomes action.payload; preparation lets the callback construct the action contents instead.
createAction be used instead of relying on generated slice actions?A standalone action creator is useful for actions that are not tied to one slice. createSlice usually generates action creators for slice reducers, while createAction directly creates one from a type string.
Follow-up: What alternative should usually be preferred for slice-owned actions? Use createSlice, which defines reducers and automatically generates corresponding action creators and action types.
createSlicecreateReducercreateAsyncThunk