Blog>
Snippets

Creating Slices with RTK 2.0 Auto-generated Action Types

Demonstrate how to define a slice with Redux Toolkit 2.0 that automatically generates action types and action creators, reducing boilerplate.
import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    incremented(state) {
      // The state is directly mutable here thanks to Immer
      return state + 1;
    },
    decremented(state) {
      return state - 1;
    }
  }
});

export const { incremented, decremented } = counterSlice.actions;
export default counterSlice.reducer;
This code defines a Redux slice for a counter feature using Redux Toolkit 2.0. The 'createSlice' function generates action creators and action types automatically based on the provided 'reducers' object.
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Counter App</title>
</head>
<body>
    <div id='app'>
        <button id='incrementBtn'>Increment</button>
        <button id='decrementBtn'>Decrement</button>
        <p>Current Count: <span id='count'>0</span></p>
    </div>
    <script src='./path_to_your_entry_point.js'></script>
</body>
</html>
This is the corresponding HTML structure for a simple counter app. It includes buttons for incrementing and decrementing the count and a paragraph to display the current count.
#app { display: flex; flex-direction: column; align-items: center; }
button { margin: 5px; }
Sample CSS to style the counter app. It centers the content and adds margin to the buttons.