Blog>
Snippets

Migrating createSlice Syntax for RTK 2.0

Modify an existing createSlice example to fit the updated API in Redux Toolkit 2.0, showcasing the new recommended patterns for defining reducers and actions.
// Redux Toolkit before 2.0
import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    incremented: state => state + 1,
    decremented: state => state - 1
  }
});

const { incremented, decremented } = counterSlice.actions;

export const { reducer } = counterSlice;
export const actions = { incremented, decremented };
This is the original `createSlice` code prior to Redux Toolkit 2.0.
// Redux Toolkit 2.0 Syntax
import { createSlice } from '@reduxjs/toolkit';

export const [slice, actions] = createSlice({
  name: 'counter',
  initialState: 0,
  cases(builder) {
    return {
      incremented: state => state + 1,
      decremented: state => state - 1,
    };
  }
});

export const reducer = slice;
// Destructure to get actions individually, if needed
const { incremented, decremented } = actions;
This code has been updated to match the Redux Toolkit 2.0 API for `createSlice`. It utilizes a tuple return with the new `cases` function to define reducer logic.