CodeBlanks Logo Icon CodeBlanks

Project: State management

Review the goal and steps of the state management project.

Project: State management

In this project you will use Redux Toolkit, Zustand and SWR together. The goal is to write a complete flow that fetches a product list, adds items to a cart and manages the cart.

The first lesson sets up a Redux Toolkit store; the second moves to Zustand; the third fetches data with SWR. Each lesson takes the previous solution as its starting code.

This structure is a small copy of real e-commerce apps; you learn state management end to end.

Project structure

The three-lesson structure is: each lesson contains the previous solution's starting code, so code accumulates. In the final lesson both data fetching and cart management work together.

In the first lesson you write a cart slice with createSlice; in the second you move it to Zustand; in the third you fetch products with SWR and add them to the cart.

This mimics the 'state migration' flow used in real projects; you learn to solve the same need with different tools.

Practice Cart slice and store

Complete the skeleton. Define cartSlice with createSlice: name: 'cart', initialState: { items: [] }, inside reducers add addItem (state, action) => state.items.push(action.payload). 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 Which library will NOT be used in this project?

  • Redux Toolkit
  • Zustand
  • SWR
  • Three.js Correct answer

Explanation: Three.js is a 3D library, not used in this project.

2 Cart slice name

Question
const cartSlice = createSlice({ name: '____', initialState: { items: [] } });
Answer
const cartSlice = createSlice({ name: 'cart', initialState: { items: [] } });

Explanation: The name field is lowercase 'cart'.

3 Project: State management: match the terms

Term Meaning
createSlice Cart slice
configureStore Sets up store
Provider Wraps app
useSelector Reads state

All lessons in Advanced