07 / 12

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

Difficulty: 5/10
prepare callback, createSlice, payload shaping

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.

Scenario Questions

0-2 years experience

  1. 1You need every action in a new slice to include a `createdAt` timestamp. How would you use a prepare callback in createSlice to achieve that?
  2. 2If you forget to return an object from the prepare function, what will the dispatched action look like?

2-5 years experience

  1. 1You added a prepare callback that generates a UUID for each new item, but the UI shows undefined IDs. Walk me through how you would debug this issue.
  2. 2Explain a scenario where you would choose to put data normalization logic in a prepare callback instead of a thunk.

5-8 years experience

  1. 1When building a feature that logs every action to an external service, would you prefer a prepare callback or a custom middleware? Discuss the trade‑offs in terms of testability and performance.
  2. 2How would you design a shared utility that multiple slices can import to standardize their prepare callbacks for error handling and logging?

8+ years experience

  1. 1Across a large codebase with dozens of slices, how would you enforce a consistent shape for action payloads (e.g., include requestId, timestamp, and correlationId) without duplicating prepare logic in each slice?
  2. 2If the organization decides to migrate from Redux Toolkit to a different state management library, what considerations around existing prepare callbacks would you surface to the migration team?

Follow-up Questions

  • What are the differences between using a prepare callback and a middleware for adding the same data?
  • Can you chain multiple prepare callbacks on the same slice, and why or why not?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.