Before we dive deeper into this lesson, let’s refresh our memory about what we’re referring to when talking about a “slice” of state.

A normal Redux application has a JS object at the top of its state tree. We refer to one key/value section of that object as a “slice”. In the following example, state.todos and state.visibilityFilter are slices.

const state = { todos: [ { id: 0, text: "Learn Redux-React", completed: true, }, { id: 1, text: "Learn Redux Toolkit", completed: false, } ], visibilityFilter: "SHOW_ALL" }

We typically define one reducer for each slice of the state. Those are called “slice reducers”. Let’s take a look at the slice reducer for the state.todos slice:

/* todosSlice.js */ const addTodo = (todo) => { return { type: 'todos/addTodo', payload: todo } } const toggleTodo = (todo) => { return { type: 'todos/toggleTodo', payload: todo } } const todos = (state = [], action) => { switch (action.type) { case 'todos/addTodo': return [ ...state, { id: action.payload.id, text: action.payload.text, completed: false } ] case 'todos/toggleTodo': return state.map(todo => todo.id === action.payload.id ? { ...todo, completed: !todo.completed } : todo ) default: return state } }

Notice that this file only deals with the state.todos data and completely ignores the state.visibilityFilter slice. Managing the state one slice at a time allows us to more effectively manage the distinct logic of each individual part of our application.

In the example above, the logic for the reducer and the action creators is all written in the same file. However, in a larger application, this logic would likely be split up even further, with the reducer logic in one file and the action creators in another.

In the next exercise, we’ll take a closer look at how we can take advantage of Redux Toolkit’s createSlice() function to further simplify the logic for us. First, let’s import it.



At the top of favoriteRecipesSlice.js in the code editor, import createSlice() from the '@reduxjs/toolkit' library.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?