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
No, the
name
of theslice
does not have to match the name of the reducer.The
createSlice
docs mentions this as: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:
And then use it in your
store.js
as:You don’t need to use the same name for both, but in RTK 2.0,
createSlice
has a newreducerPath
option that will default toname
.It also ships with a new
combineSlices
api that will allow you to just inject slices into a new parent slice – which uses thatreducerPath
.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.