CodeBlanks Logo Icon CodeBlanks

Redux Toolkit store

Set up a product slice and store with Redux Toolkit.

Redux Toolkit store setup

In this lesson you set up a store with configureStore and wrap the app with Provider. The cart slice connects to the store; components access it via useSelector and useDispatch.

The starting code contains the previous lesson's solution; you add the store and Provider code. This is the natural continuation of the project flow.

The RTK store ships with redux-thunk; no extra middleware is needed for async. DevTools are auto-enabled.

useSelector and useDispatch

In components you read state with useSelector and dispatch actions with useDispatch. For example const items = useSelector((state) => state.cart.items) reads the cart.

To add a product you get const dispatch = useDispatch() and call dispatch(addItem(product)). RTK action creators auto-add the payload.

A selector triggers render only when the relevant piece changes; fine-grained selectors boost performance.

Practice Set up store and Cart component

Complete the skeleton. Create store with configureStore; reducer: { cart: cartReducer }. Import cartReducer from './cartSlice'. Add export default store.

Starter code

App.jsx
import { configureStore } from '@reduxjs/toolkit';
import cartReducer from './cartSlice';

// Define store here

Sample solution

App.jsx
import { configureStore } from '@reduxjs/toolkit';
import cartReducer from './cartSlice';

const store = configureStore({
  reducer: {
    cart: cartReducer,
  },
});

export default store;

Questions and answers

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

1 What does Provider do?

App.jsx
Provider = store + app.
  • Creates the store
  • Connects the store to the app Correct answer
  • Loads CSS
  • Runs tests

Explanation: Provider connects the store to the app.

2 useSelector call

Question
const items = ____((state) => state.cart.items);
Answer
const items = useSelector((state) => state.cart.items);

Explanation: useSelector reads state.

3 Redux Toolkit store: match the terms

Term Meaning
configureStore Sets up store
Provider Wraps app
useSelector Reads state
addItem Action creator

All lessons in Advanced