Blog>
Snippets

Migrating to Redux Toolkit 2.0 from Redux Toolkit 1.x

Show a step-by-step code example of migrating existing Redux logic using Redux Toolkit 1.x to the new methods and APIs available in Redux Toolkit 2.0.
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers';

const store = configureStore({
  reducer: rootReducer,
  // You may include any middleware or enhancers here as needed
});

export default store;
This is how you typically set up the store with Redux Toolkit 1.x. The rootReducer would be a combination of all your slice reducers.
import { createSlice } from '@reduxjs/toolkit';

// Assuming a todo application
export const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    addTodo(state, action) {
      // Mutate the state directly, RTK uses Immer under the hood
      state.push(action.payload);
    },
    // ...other reducers
  },
});

export const { addTodo } = todosSlice.actions;
This is a Redux Toolkit 1.x slice with a reducer and corresponding actions. RTK allows us to write mutable logic in reducers which is converted to immutable updates under the hood using Immer.
import { configureStore } from '@reduxjs/toolkit';
import todosReducer from '../features/todos/todosSlice';

// Now using createReducer or createSlice with the new matcher utilities
export const store = configureStore({
  reducer: {
    todos: todosReducer,
  },
  // Middleware and enhancers can still be added here
});
In Redux Toolkit 2.0, the way you create the store remains largely unchanged.
import { createSlice, createAction } from '@reduxjs/toolkit';

// Define actions using createAction
export const addTodo = createAction('todos/add');

export const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  extraReducers: (builder) => {
    builder.addCase(addTodo, (state, action) => {
      state.push(action.payload);
    });
    // Add cases for other actions
  },
});
In Redux Toolkit 2.0, if you need more control over action creation, or if you're working with actions that aren't directly tied to a slice, you can use createAction. Here's how to define the same todos slice, but with a separate action defined outside the slice.
There are no specific CSS or HTML code changes related to migrating from Redux Toolkit 1.x to 2.0, as this is purely a JavaScript-level change.