Search code examples
javascriptreduxreact-reduxredux-toolkit

What's the difference between below two cofigurestore in redux toolkit


I am new to Redux Toolkit and was following the docs. I was configuring the store and I saw this approach in quick overview sections https://redux-toolkit.js.org/usage/usage-guide#simplifying-store-setup-with-configurestore

import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './reducers'

const store = configureStore({
  reducer: rootReducer,
})

export default store

but in the docs for quick start I also saw this approach https://redux-toolkit.js.org/tutorials/quick-start

import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
})

Why are these two different assuming we are exporting slicename.reducers and one is nested using slice name while other is directly being assigned as a reducer?

Is reducer: { counter: counterReducer, }, approach taken if there are multiple reducers and to combine them?


Solution

  • The reducer option of configureStore function can be a function or an object. The source code configureStore.ts#L162:

    if (typeof reducer === 'function') {
      rootReducer = reducer
    } else if (isPlainObject(reducer)) {
      rootReducer = combineReducers(reducer) as unknown as Reducer<S, A>
    }
    
    // ... 
    
    return createStore(rootReducer, preloadedState, composedEnhancer)
    

    As you can see if you pass an object full of reducers for each state slice. It will use redux combineReducers to combine them. The rootReducer will be passed in the createStore function at the end, see configureStore.ts#L214.

    That's the difference between them. More often, we use the second approach, dividing a state tree into multiple state slices. And combine them into a root reducer. But if your application is simple, and doesn't need to maintain a complex state, then you don't need to split the state tree, a root reducer is enough.