Search⌘ K
AI Features

Define Redux Actions with createAction

Explore how to define Redux actions efficiently using the createAction API in Redux Toolkit. Learn to combine action type and creator creation, utilize the .type property, and handle payloads with ease, streamlining your Redux code.

The createAction API

The API for createAction is simple but very much needed.

Consider the typical way to create a Redux action. We’ve followed a similar pattern with Flappy.

(i) Create a type string.

Javascript (babel-node)
export const UPDATE_MOOD = "UPDATE_MOOD";

(ii) Create the action creator.

Javascript (babel-node)
export const updateCatMood = (payload) => ({
type: UPDATE_MOOD,
payload,
});

Action objects have a somewhat fixed shape, making it obvious to automate its creation. With createAction, we can merge the steps above into one. Just invoke createAction with an action type.

Javascript (babel-node)
export const UPDATE_MOOD = "UPDATE_MOOD";
export const updateCatMood = createAction(UPDATE_MOOD);

While the utility name says createAction, it ...