Blog>
Snippets

Using createSlice to Simplify Reducers and Actions

A practical example showing how to use createSlice from Redux Toolkit to concurrently generate actions and reducers in Redux v5.0.1 for a todo app module.
import { createSlice } from '@reduxjs/toolkit';

// Define initial state
const initialState = {
  todos: [],
  status: 'idle',
};

// Create the todos slice using createSlice
const todosSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    addTodo: (state, action) => {
      // Reducer to add a new todo
      state.todos.push({
        id: state.todos.length + 1,
        text: action.payload,
        completed: false,
      });
    },
    toggleTodo: (state, action) => {
      // Reducer to toggle the completed status of a todo
      const todo = state.todos.find(todo => todo.id === action.payload);
      if (todo) {
        todo.completed = !todo.completed;
      }
    },
    removeTodo: (state, action) => {
      // Reducer to remove a todo by id
      state.todos = state.todos.filter(todo => todo.id !== action.payload);
    }
  },
});

// Export generated actions
export const { addTodo, toggleTodo, removeTodo } = todosSlice.actions;

// Export the reducer
export default todosSlice.reducer;
This code defines a todos slice with three reducers for adding, toggling, and removing todos. These actions are automatically generated, and the corresponding reducer functions are included.