Blog>
Snippets

Refactoring with Redux Toolkit

Show the process of refactoring a traditional Redux setup to use Redux Toolkit, which includes utilities that can help in preventing type errors.
// Traditional Redux setup
// actions.js
export const ADD_TODO = 'ADD_TODO';
export function addTodo(text) {
  return { type: ADD_TODO, text };
}

// reducer.js
import { ADD_TODO } from './actions';
const initialState = [];
function todosReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TODO:
      return [...state, { text: action.text, completed: false }];
    default:
      return state;
  }
}

// store.js
import { createStore } from 'redux';
import todosReducer from './reducer';
const store = createStore(todosReducer);

// Dispatch
store.dispatch(addTodo('Learn Redux'));
This is the traditional way of setting up Redux with separate files for actions, types, and reducers. An action type ADD_TODO is defined, along with an action creator addTodo and a todosReducer to handle updates to the state. The store is then created with createStore.
// Refactored Redux using Redux Toolkit
// slices.js
import { createSlice, configureStore } from '@reduxjs/toolkit';

const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    addTodo: (state, action) => {
      state.push({ text: action.payload, completed: false });
    },
  },
});

export const { addTodo } = todosSlice.actions;
export default todosSlice.reducer;

// store.js
import { configureStore } from '@reduxjs/toolkit';
import todosReducer from './slices';
const store = configureStore({
  reducer: {
    todos: todosReducer,
  },
});

// Dispatch
store.dispatch(addTodo('Learn Redux Toolkit'));
This code is refactored to use Redux Toolkit. Using createSlice to combine action types, action creators, and reducers into one. The todosSlice handles the state updates concisely. The store is created using configureStore which enables additional checks and features. An action is dispatched with the new addTodo action creator.