skip to Main Content

I hope that finally someone can answer my question … which is more of a general "good to know" question rather than a vitally important one 🙂

I cannot for the life of me find a definite answer to my question whether or not the name property of a Redux Toolkit slice has to correspond to the property name of the reducer in the configured store. None of the tutorials I read and viewed and even the docs show the connection between these … it’s just that EVERY single tutorial used the same name for both

Example:

counterSlice.js

export const counterSlice = createSlice({
  name: "counter",
  initialState: { count: 0 }
  ...
});

store.js

import counterReducer from "../features/counter/counterSlice";

export const store = configureStore({
  reducer: {
    counter: counterReducer,            // does this "counter" have to be the same as the name in the slice?
  }
});

Component:

import { useSelector } from "react-redux";

const count = useSelector((state) => state.counter.count);   // and this "counter" also? If NOT, what is the connection?

2

Answers


  1. … whether or not the name property of a Redux Toolkit slice has to correspond to the property name of the reducer in the configured store.

    No, the name of the slice does not have to match the name of the reducer.


    The createSlice docs mentions this as:

    name

    A string name for this slice of state. Generated action type constants will use this as a prefix.

    The last part is the most important way the name is used. For example, the Redux Dev Tools will the name of the slice as prefix for every dispatched action.


    However, nobody will prevent you from creating a slice like so:

    export const FooBar = createSlice({
        name: 'okidoki',
        initialState: {
            data: {},
            photo: {}
        },
        reducers: { 
        }
    });
    

    And then use it in your store.js as:

    import FooBar from './SomeReducerFile.js';
    
    export default createStore(
        combineReducers({
            employee: FooBar
        }),
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    );
    
    Login or Signup to reply.
  2. You don’t need to use the same name for both, but in RTK 2.0, createSlice has a new reducerPath option that will default to name.
    It also ships with a new combineSlices api that will allow you to just inject slices into a new parent slice – which uses that reducerPath.

    So while it’s not necessary, it’s a good default and in most cases you probably shouldn’t deviate unless you have a reason.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search