Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 41 ยท Core Concepts

Actions and Action Creators in Redux

Learn what a Redux action is, how to name types, structure payloads, write action creators and think of actions as events instead of setters. Live examples included.

An action is a plain JavaScript object that says something happened. It is the only way to tell Redux that the state should change. Actions are small, boring and easy to log, and that is exactly the point: the whole history of your app can be written down as a list of them.

An action creator is a function that builds an action object for you. It saves typing, avoids typos in the type string and gives you one place to change an action's shape. In Redux Toolkit action creators are generated for you, but they are the same thing you will write by hand in this lesson.

The shape of an action

Every action needs a type. In Redux 5 the type must be a string. Everything else is up to you, but the community convention (known as the Flux Standard Action) is:

JavaScript
{
  type: 'todos/added',        // required: what happened
  payload: { id: 1, text: 'Learn Redux' }, // optional: the data
  meta: { source: 'keyboard' },            // optional: extra info about the action
  error: true,                             // optional: payload is an error
}
  • type: a string that names the event.
  • payload: the data the reducer needs. Keep it as small as it can be.
  • meta and error: used rarely. Redux Toolkit's thunks use meta to carry request ids and arguments.

Actions should be serializable (see State and Immutability): no functions, class instances or promises inside them.

Naming action types

The usual convention is domain/eventName, in the past tense, because actions describe something that already happened:

Good Why
todos/added The event is named; the reducer decides the effect
cart/itemRemoved Reads like a log entry
auth/loggedOut Describes the user's action
posts/fetchFailed A result, not a command

Avoid SET_TODOS or todos/setItems: they describe how to change state, not what happened, and push logic into components. See "events, not setters" below.

Older code defines constants const ADD_TODO = 'ADD_TODO'. With Redux Toolkit you do not need them, because the action creators carry the type (added.type).

Action creators

An action creator is just a function that returns an action. Call it where you dispatch, instead of writing the object by hand:

JS Writing action creators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last creator generates the id before the action is dispatched. A reducer must be pure (the same input always gives the same output), so impure values such as ids, random numbers and timestamps are created in the creator and travel in the payload. Redux Toolkit formalises this with a prepare callback (createAction).

Dispatching actions

You send an action to the store with store.dispatch(action). dispatch returns the action it was given, which is occasionally useful. In a React component you call the function returned by useDispatch() (see useDispatch and Events).

JS Dispatch checks what it is given

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The most common beginner bug is the first one: dispatch(added) instead of dispatch(added('text')). You pass the result of the action creator, not the creator itself.

Events, not setters

Compare two ways to model "the user pressed Add to cart" for an item that may already be in the cart:

JavaScript
// setter style: the component does the logic
dispatch({ type: 'cart/setItems', payload: [...items, newItem] });

// event style: the reducer does the logic
dispatch({ type: 'cart/itemAdded', payload: newItem });

In the setter version every component that adds items must know how to merge, count and avoid duplicates, and a bug in one place diverges from the others. In the event version one reducer owns the rules, and the action log tells a readable story. Prefer few, meaningful events, and let reducers decide what each event means. The Redux style guide recommends the same.

A related idea: one event can be handled by several reducers. When the user logs out, a single auth/loggedOut action can reset the cart, profile and settings slices, without three separate dispatches.

Keep payloads small

Send what the reducer needs, not what the component happens to have. Send an id, not a whole object that is already in the store; send the changed fields, not the entire form. Small payloads are easier to read in the DevTools, cheaper to log and less likely to contain non-serializable values.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the only required property of a Redux action?

    Every action must have a type. In Redux 5 it must be a string. payload and meta are conventions.
  2. 2. Where should a new todo's id be generated so the reducer stays pure?

    Impure values are created before the action reaches the reducer, so replaying the same actions always gives the same state.
  3. 3. Which action type follows the recommended convention?

    Use domain/eventName in the past tense: it describes what happened and reads well in the DevTools.
  4. 4. What is wrong with store.dispatch(todoAdded)?

    You dispatch the result of the action creator: dispatch(todoAdded('text')). Passing the function itself is an invalid action (unless thunk middleware is present).

Summary

  • An action is a plain, serializable object with a string type, usually plus a payload.
  • Name types domain/eventName in the past tense; model events, not setters.
  • Action creators build actions and are the right place for ids, timestamps and other impure values.
  • dispatch(action) sends the action to the store and returns it; always dispatch the result of the creator.
  • One action can be handled by many reducers.

Next: Reducers in Depth