07 / 12

What is the prepare callback in createSlice and how is it used?

In Redux Toolkit, the prepare callback allows you to customize action’s payload before it reaches the reducer. It is used inside a reducer definition within createSlice() and returns an object containing payload, and optionally, meta and error fields.

When to Use the prepare Callback
  1. 1

    To preprocess or format arguments before passing them as the action payload.

  2. 2

    To include additional fields such as timestamps or IDs along with the payload.

  3. 3

    To maintain clean reducer logic by separating payload creation from state updates.

Example: Using prepare to Add Metadata

Here, the prepare callback formats the payload with an auto-generated ID and timestamp before the action reaches the reducer, keeping the reducer focused solely on updating the state.