Redux-toolkit: When to use createReducer() vs createSlice()

Created on 20 Jan 2019  路  4Comments  路  Source: reduxjs/redux-toolkit

I don't feel it's clear from the documentation when to use createReducer() and when to use createSlice(). There are a lot of cases where either could be used with createSlice() being less verbose. Is the idea that createSlice() is the easiest choice unless you need more control over the action creators? I'm coming from vanilla redux but also see how this could be confusing to a new user.

Most helpful comment

Yeah, that's roughly the case.

As a more specific example, let's say you want to handle async request status (ie, "REQUEST_STARTED / SUCCESS / FAILURE" actions. That doesn't work well with createSlice() right now, because it tries to generate action creators and action types based on the reducer names, and the reducers _only_ respond to those actions. So, you'd probably have to do:

const requestStarted = createAction("REQUEST_STARTED");
const requestSuccess = createAction("REQUEST_SUCCESS");
const requestFailure = createAction("REQUEST_FAILURE");

const reducer = createReduce(initialState, {
    [requestStarted]: () => {},
    [requestSuccess ]: () => {},
    [requestFailure ]: () => {},
});

That said, I've got a couple ideas on both fronts I want to play with (possibly even later today).

All 4 comments

Yeah, that's roughly the case.

As a more specific example, let's say you want to handle async request status (ie, "REQUEST_STARTED / SUCCESS / FAILURE" actions. That doesn't work well with createSlice() right now, because it tries to generate action creators and action types based on the reducer names, and the reducers _only_ respond to those actions. So, you'd probably have to do:

const requestStarted = createAction("REQUEST_STARTED");
const requestSuccess = createAction("REQUEST_SUCCESS");
const requestFailure = createAction("REQUEST_FAILURE");

const reducer = createReduce(initialState, {
    [requestStarted]: () => {},
    [requestSuccess ]: () => {},
    [requestFailure ]: () => {},
});

That said, I've got a couple ideas on both fronts I want to play with (possibly even later today).

Thanks. I decided to stick with using createReducer() in the end as I felt the gains of using createSlice() were quite small and it wouldn't always be possible to anticipate needing custom action creators. From my perspective, createReducer() already greatly simplifies working with Redux.

Can this be closed? Seems like the question has been answered.

Just wanted to update this thread in case anyone else lands here with the same question. You can specify a customize the payload values in createSlice by returning an object instead of a function in the reducer object.

It's documented here - https://redux-toolkit.js.org/api/createslice/#customizing-generated-action-creators

Was this page helpful?
0 / 5 - 0 ratings