Blog>
Snippets

Migrating to Redux Toolkit in v5.0.0

Explain how to transition existing Redux logic to the Redux Toolkit, emphasizing the use of configureStore and createReducer to simplify setup and reduce boilerplate.
import { configureStore } from '@reduxjs/toolkit';

// ... your other imports

const store = configureStore({
  reducer: {
    // your reducers go here
  },
  // middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(yourMiddleware),
  // ... other store setup like enhancers
});

export default store;
The configureStore function from Redux Toolkit simplifies the store configuration process. It automatically sets up the Redux DevTools extension and includes thunk middleware by default. Here, you should pass your reducers as an object to the 'reducer' property.
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  // initial state values
};

// Example slice using createSlice
const exampleSlice = createSlice({
  name: 'example',
  initialState,
  reducers: {
    // define reducers here
  },
});

export const { actions, reducer } = exampleSlice;
createSlice from Redux Toolkit allows you to create a slice of the state with a corresponding reducer and actions. The object contains a name, the initial state, and an object of reducer functions.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Example action using createAction
const increment = createAction('increment');

// Example reducer using createReducer
// The initial state for the reducer
const initialState = 0;

const counterReducer = createReducer(initialState, {
  [increment]: (state, action) => state + 1,
  // other action handlers
});

export default counterReducer;
Using createAction to define an action and createReducer to define a reducer. createReducer accepts an initial state and an action map where the keys are the actions processed by this reducer.
import { createReducer } from '@reduxjs/toolkit';
import { addTodo, toggleTodo } from './todoActions';

const initialState = [];

// Reducer using createReducer
const todosReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(addTodo, (state, action) => {
      // logic to add a todo
    })
    .addCase(toggleTodo, (state, action) => {
      // logic to toggle a todo
    });
    // add more cases as needed
});

export default todosReducer;
createReducer can also use a builder callback pattern which allows you to chain calls to addCase to respond to different action types with different state update logic.