Blog>
Snippets

Creating Slice Reducers with createSlice

Provide an example of converting traditional Redux reducers and action creators into a slice reducer using Redux Toolkit's createSlice, indicating how to simplify the reducer logic and actions.
import { createSlice } from '@reduxjs/toolkit';

// Define the initial state of the counter
const initialState = {
  value: 0,
};

// Create a slice with reducers and actions using createSlice
const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: state => {
      // Reducer logic to increment the counter
      state.value += 1;
    },
    decrement: state => {
      // Reducer logic to decrement the counter
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      // Reducer logic to increment counter by specific amount
      state.value += action.payload;
    }
  }
});

// Export generated action creators
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// Export the reducer
export default counterSlice.reducer;
This code defines a counter slice using Redux Toolkit's createSlice function, which includes the slice name ('counter'), the initial state, and the reducer functions. It also exports the action creators and the reducer. The increment, decrement, and incrementByAmount actions within the slice are used to alter the state of the counter.