Search⌘ K
AI Features

Creating Slices of State with createSlice

Explore how to use Redux Toolkit's createSlice API to create and manage slices of application state. Learn to define initial state, reducers, and auto-generate action creators to streamline Redux development and improve state handling.

We'll cover the following...

The createSlice API

Since you already know the purpose of createSlice, let’s get right into its API.

Javascript (babel-node)
const sliceObject = createSlice({
name: 'aSliceName',
initialState: someInitialStateValue,
reducers: {
// object of case reducers
}
})

createSlice is invoked with an object of the shape seen above. The name field represents the slice name, initialState is the initial state for the slice of state, and reducers is an object of case reducers where each value handles a certain action type.

Don’t worry if you don’t fully understand it. Let’s refactor Flappy to use createSlice, and it’ll all come together nicely!

The Flappy app has a simple application state. Let’s create a single slice of state to represent this:

Javascript (babel-node)
import { createSlice } from "@reduxjs/toolkit";
const flappyMoodSlice = createSlice({
});

Let’s ...