DEV Community

Aditya Singh
Aditya Singh

Posted on

4

Latest Redux Toolkit: Using the Builder Callback Notation in createReducer đź’»

In recent updates to Redux Toolkit, the way we define reducers has evolved. The traditional object notation for createReducer has been replaced by a more flexible and powerful builder callback notation. This change is designed to offer better TypeScript support and more control over reducer logic. Let's dive into the difference and see how to upgrade your code.

The Old Way: Object Notation

Previously, we could define our reducers using an object where keys were action types and values were the corresponding reducer functions. Here’s an example:

import { createReducer } from '@reduxjs/toolkit';

let id = 0;

const tasksReducer = createReducer([], {
  ADD_TASK: (state, action) => {
    state.push({
      id: ++id,
      task: action.payload.task,
      completed: false,
    });
  },
  REMOVE_TASK: (state, action) => {
    const index = state.findIndex((task) => task.id === action.payload.id);
    if (index !== -1) {
      state.splice(index, 1);
    }
  },
  COMPLETE_TASK: (state, action) => {
    const index = state.findIndex((task) => task.id === action.payload.id);
    if (index !== -1) {
      state[index].completed = true;
    }
  },
});

export default tasksReducer;

Enter fullscreen mode Exit fullscreen mode

The New Way: Builder Callback Notation

With the new builder callback notation, we define reducers using a builder pattern. This approach provides a more structured and scalable way to handle actions, especially in larger applications.

import { createReducer } from '@reduxjs/toolkit';

let id = 0;

const tasksReducer = createReducer([], (builder) => {
  builder
    .addCase('ADD_TASK', (state, action) => {
      state.push({
        id: ++id,
        task: action.payload.task,
        completed: false,
      });
    })
    .addCase('REMOVE_TASK', (state, action) => {
      const index = state.findIndex((task) => task.id === action.payload.id);
      if (index !== -1) {
        state.splice(index, 1);
      }
    })
    .addCase('COMPLETE_TASK', (state, action) => {
      const index = state.findIndex((task) => task.id === action.payload.id);
      if (index !== -1) {
        state[index].completed = true;
      }
    });
});

export default tasksReducer;
Enter fullscreen mode Exit fullscreen mode

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay