Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 41 ยท Testing and Tooling

Migrating Legacy Redux to Redux Toolkit

Modernize an older Redux codebase step by step: switch to configureStore, replace switch reducers with createSlice, remove action constants, use hooks and RTK Query, one feature at a time.

Many Redux codebases were written before Redux Toolkit (RTK): createStore, action type constants, switch-statement reducers, connect() and hand-written thunks. The good news is that RTK is designed for incremental adoption. You do not need a rewrite: old and new code run side by side in one store, and each step makes the code shorter. The official createStore function from redux is also marked deprecated in Redux 5 (it still works), so the steps below also remove a deprecation warning.

The legacy style

This is typical code for one feature, shown read-only because it does not use Toolkit:

JavaScript
// Legacy Redux (read-only)
const ADD_TODO = 'todos/ADD_TODO';
const TOGGLE_TODO = 'todos/TOGGLE_TODO';

export const addTodo = (text) => ({ type: ADD_TODO, payload: { id: nextId++, text } });
export const toggleTodo = (id) => ({ type: TOGGLE_TODO, payload: id });

export default function todos(state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [...state, { ...action.payload, done: false }];
    case TOGGLE_TODO:
      return state.map((t) => (t.id === action.payload ? { ...t, done: !t.done } : t));
    default:
      return state;
  }
}

The migration path

flowchart TD
  A["1. Update packages"] --> B["2. configureStore"]
  B --> C["3. createSlice per feature"]
  C --> D["4. Hooks instead of connect"]
  D --> E["5. createAsyncThunk / RTK Query"]
  E --> F["6. Entity adapters, listeners"]

Every step leaves the app working, so you can stop at any point.

Step 1: update and run the tests

Move to Redux 5 / React-Redux 9 / RTK 2 (read the release notes: breaking changes include ESM-first packages, middleware must be a callback, and action type strings are now typed as string). Make sure your tests pass before changing anything else.

Step 2: replace createStore with configureStore

JavaScript
// Before (read-only)
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk, logger)));

// After (read-only)
const store = configureStore({
  reducer: rootReducer,                       // your existing combineReducers result still works
  middleware: (gdm) => gdm().concat(logger),  // thunk is already included
});

You gain: automatic DevTools, thunk, and the development checks for mutation and non-serializable values. Expect those checks to reveal real latent bugs (state mutated in an old reducer, a Date in an action). Fix them or, for the rare intentional case, narrowly ignore them.

Step 3: one slice at a time with createSlice

createSlice generates the action creators and action types and allows Immer "mutation". Convert one feature, keep the rest.

JS Before and after, side by side

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real createSlice is the same shape; the difference is Immer, so the reducers become:

JavaScript
// Real Redux Toolkit (read-only)
const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    added: (state, action) => { state.push({ ...action.payload, done: false }); },
    toggled: (state, action) => {
      const todo = state.find((t) => t.id === action.payload);
      if (todo) todo.done = !todo.done;
    },
  },
});

Mixing is fine: the slice's reducer goes into the same combineReducers object next to legacy reducers. If other legacy code still imports the old constants (ADD_TODO), make the slice react to them with extraReducers until those callers are migrated.

Typing note: keep action type strings stable during migration if anything depends on them (logs, analytics, tests). createSlice names them name/reducerKey, so choose name and keys to match, for example 'todos' and added give todos/added.

Step 4: hooks instead of connect

connect(mapState, mapDispatch)(Component) works but is verbose and harder to type. Components migrate one by one:

JSX
// Before (read-only)
const mapState = (state) => ({ todos: selectVisibleTodos(state) });
export default connect(mapState, { toggleTodo })(TodoList);

// After (read-only)
export default function TodoList() {
  const todos = useSelector(selectVisibleTodos);
  const dispatch = useDispatch();
  return todos.map((t) => <li key={t.id} onClick={() => dispatch(toggled(t.id))}>{t.text}</li>);
}

Hooks and connect can coexist in one app. Move the logic from mapState into named selectors first; that step alone removes a lot of duplication.

Step 5: async code

Replace hand-written REQUEST/SUCCESS/FAILURE constants and thunks with createAsyncThunk. For data that comes from a server and mostly needs caching (lists, details), go further and replace the slice and thunk with RTK Query endpoints. This often removes 60 to 80 percent of the code for a feature. Migrate the endpoint, switch the components, then delete the old slice.

Step 6: polish

  • Convert array state to entity adapters where you look things up by id.
  • Move "do X when action Y happens" middleware to listeners.
  • Add TypeScript, starting with the store's inferred types and typed hooks.
  • Delete unused redux-* helper libraries (redux-thunk, reselect, redux-devtools-extension, immer) from package.json: RTK re-exports what you need.

What to leave alone

  • Reducers that are already pure, tested and rarely touched: converting them gives little benefit.
  • Sagas or observables that work: RTK does not require removing them (they can run beside the RTK middleware). Migrate only if they become a burden.
  • Do not change the state shape and the syntax in one commit. Convert first, reshape (normalization) afterwards, so a failing test points at one cause.

A safe workflow

  1. Write or confirm tests for the feature (dispatch actions, read selectors).
  2. Migrate that feature; run the tests unchanged.
  3. Fix what the new development checks report.
  4. Commit per feature, so you can revert one without losing the rest.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Can legacy reducers and createSlice reducers live in the same store?

    A slice's reducer is an ordinary reducer function that can sit next to legacy ones.
  2. 2. What do you gain immediately by replacing createStore with configureStore?

    These defaults are configured for you.
  3. 3. Why keep action type strings stable during migration?

    Changing names and syntax together makes failures hard to trace.
  4. 4. What is often the biggest simplification for server data?

    RTK Query generates the cache, status and hooks.

Summary

  • Migrate incrementally: packages, configureStore, createSlice, hooks, async, then polish.
  • Old and new reducers coexist in one store; convert feature by feature.
  • Fix the problems the new development checks reveal.
  • Prefer RTK Query for server data and keep stable action names while converting.
  • Leave pure, stable, rarely edited code alone and commit per feature.

Next: Project: a todo list with Redux