Summary - Redux Toolkit
- React course
- Advanced
- Lesson 24/56
- 5 min
Set up a cart slice and store and connect them to a component.
Summary - Redux Toolkit
In this group you learned what RTK is, how to write a slice with createSlice, and how to set up a store with configureStore. Now it's time to combine them.
Typical flow: write a cart slice with createSlice; connect it to a store with configureStore; wrap the app with Provider; components read and change the cart with useSelector and useDispatch.
In the next step you will write a complete cart flow.
Practice Write Cart component
Complete the skeleton. Write a Cart component. Read state.cart.items with useSelector (state parameter). Get dispatch with useDispatch. Render <ul> with items.map((item, i) => <li key={i}>{item.name}</li>). Add export default.
Starter code
import { useSelector, useDispatch } from 'react-redux';
import { addItem } from './cartSlice';
// Write Cart hereSample solution
import { useSelector, useDispatch } from 'react-redux';
import { addItem } from './cartSlice';
function Cart() {
const items = useSelector((state) => state.cart.items);
const dispatch = useDispatch();
return (
<ul>
{items.map((item, i) => (
<li key={i}>{item.name}</li>
))}
</ul>
);
}
export default Cart;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which topic was NOT covered in this group?
Three topics were covered; RSC was not.- createSlice
- configureStore
- Provider
- Server Components Correct answer
Explanation: Server Components were not covered in this group.
2 useDispatch call
const ____ = useDispatch();
const dispatch = useDispatch();
Explanation: dispatch sends actions.