CodeBlanks Logo Icon CodeBlanks

What is Redux Toolkit?

Learn that Redux Toolkit makes Redux easier.

What is Redux Toolkit?

Redux Toolkit (RTK) is the official, recommended package for Redux. It cuts the boilerplate of standard Redux and makes slice, store and async thunks easy.

With RTK a single createSlice call produces the reducer, action creators and immutability at once. This collapses dozens of classic Redux lines into a few.

RTK ships with immer, redux-thunk and reselect built in; no extra setup needed.

The slice concept

A slice is the object that holds the reducer and actions responsible for one part of the app. For example cartSlice holds addItem, removeItem actions and the reducer for the cart.

You define a slice with RTK's createSlice; it auto-generates actions and reducer. The name field is the slice name, initialState is the starting state, and reducers defines the behaviours.

Multiple slices are combined in one store; each slice manages its own part.

Practice Define cartSlice

Complete the skeleton. Define cartSlice with createSlice. name: 'cart', initialState: { items: [] }, inside reducers add addItem (state, action) => state.items.push(action.payload). Then add export const { addItem } = cartSlice.actions; and export default cartSlice.reducer;.

Starter code

App.jsx
import { createSlice } from '@reduxjs/toolkit';

// Define cartSlice here

Sample solution

App.jsx
import { createSlice } from '@reduxjs/toolkit';

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [] },
  reducers: {
    addItem: (state, action) => {
      state.items.push(action.payload);
    },
  },
});

export const { addItem } = cartSlice.actions;
export default cartSlice.reducer;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does Redux Toolkit reduce?

App.jsx
A single createSlice call replaces dozens of lines.
  • Boilerplate code Correct answer
  • Runtime
  • File size to zero
  • Number of tests

Explanation: RTK reduces boilerplate code.

2 createSlice import

Question
import { create____ } from '@reduxjs/toolkit';
Answer
import { createSlice } from '@reduxjs/toolkit';

Explanation: createSlice is imported from RTK.

3 What is Redux Toolkit: match the terms

Term Meaning
createSlice Creates slice
reducers Behaviours
initialState Starting state
name Slice name

All lessons in Advanced