Write slices and dispatch actions
Create a slice for a coherent domain
A slice groups a domain’s initial state and its update rules. createSlice generates action creators from named case reducers, with namespaced action types. In the stationery cart, each product has one canonical record keyed by ID; ids specifies display order. This avoids copying the same quantity into several components. The stock limit is a fictional local rule, not inventory authorization.
import React, { useState } from 'react';import { configureStore, createSlice } from '@reduxjs/toolkit';import { Provider, useSelector, useDispatch } from 'react-redux';function nextQuantity(current, delta, limit) { if (!Number.isInteger(delta)) return current; return Math.min(limit, Math.max(0, current + delta));}const cartSlice = createSlice({name:'cart',initialState:{ids:['pen','pad'],byId:{pen:{id:'pen',name:'Pen',priceCents:250,quantity:0,limit:5},pad:{id:'pad',name:'Pad',priceCents:400,quantity:0,limit:3}}},reducers:{ quantityChanged(state,action){ const {id,delta}=action.payload; if (!Object.hasOwn(state.byId,id)) return; const item=state.byId[id]; item.quantity=nextQuantity(item.quantity,delta,item.limit); }, cleared(state){for(const id of state.ids) state.byId[id].quantity=0;}}});const {quantityChanged,cleared}=cartSlice.actions;function makeStore(){return configureStore({reducer:{cart:cartSlice.reducer},devTools:false});}function Panel(){const item=useSelector(s=>s.cart.byId.pen);const dispatch=useDispatch();return <section><h2>{item.name}</h2><p>Quantity: {item.quantity}</p><button disabled={item.quantity===item.limit} onClick={()=>dispatch(quantityChanged({id:'pen',delta:1}))}>Add pen</button><button disabled={item.quantity===0} onClick={()=>dispatch(quantityChanged({id:'pen',delta:-1}))}>Remove pen</button></section>;}export default function App(){const [store]=useState(makeStore);return <Provider store={store}><Panel /></Provider>;}The first click dispatches an action with type cart/quantityChanged and payload {id: "pen", delta: 1}. The case reducer finds the record, applies a bounded integer update and changes the draft quantity. The unknown-ID guard prevents creating arbitrary entries; invalid noninteger deltas leave quantity unchanged. The add button stops at five. This is a fixed synthetic catalogue, not a validator for hostile requests. The server must enforce real prices, quantities and permissions.
Understand Immer draft boundaries
import React, { useState } from 'react';import { configureStore, createSlice } from '@reduxjs/toolkit';import { Provider, useSelector, useDispatch } from 'react-redux';function nextQuantity(current, delta, limit) { if (!Number.isInteger(delta)) return current; return Math.min(limit, Math.max(0, current + delta));}const cartSlice = createSlice({name:'cart',initialState:{ids:['pen','pad'],byId:{pen:{id:'pen',name:'Pen',priceCents:250,quantity:0,limit:5},pad:{id:'pad',name:'Pad',priceCents:400,quantity:0,limit:3}}},reducers:{ quantityChanged(state,action){ const {id,delta}=action.payload; if (!Object.hasOwn(state.byId,id)) return; const item=state.byId[id]; item.quantity=nextQuantity(item.quantity,delta,item.limit); }, cleared(state){for(const id of state.ids) state.byId[id].quantity=0;}}});const {quantityChanged,cleared}=cartSlice.actions;function makeStore(){return configureStore({reducer:{cart:cartSlice.reducer},devTools:false});}function Row({id}){ const item=useSelector(state=>state.cart.byId[id]); const dispatch=useDispatch(); return <li>{item.name}: {item.quantity} <button type="button" aria-label={'Add '+item.name} disabled={item.quantity===item.limit} onClick={()=>dispatch(quantityChanged({id,delta:1}))}>+</button> <button type="button" aria-label={'Remove '+item.name} disabled={item.quantity===0} onClick={()=>dispatch(quantityChanged({id,delta:-1}))}>−</button></li>;}function Panel(){const dispatch=useDispatch();const ids=useSelector(s=>s.cart.ids);return <section><ul>{ids.map(id=><Row key={id} id={id}/>)}</ul><button onClick={()=>dispatch(cleared())}>Clear cart</button></section>;}export default function App(){const [store]=useState(makeStore);return <Provider store={store}><Panel /></Provider>;}Immer supplies a temporary draft inside RTK case reducers. Updating a draft field produces an immutable next state while retaining unaffected references where possible. Do not retain the draft or use draft mutation in a normal React state setter. A case reducer may mutate its draft or return a replacement value; do not do both in the same execution. For example, an expression-bodied reducer returning state.items.push(value) accidentally returns the array length as well as changing the draft; use a block body. Clearing this cart resets quantities while leaving the catalogue intact.
Plain actions and serializable data
import React, { useState } from 'react';import { configureStore, createSlice } from '@reduxjs/toolkit';import { Provider, useSelector, useDispatch } from 'react-redux';function nextQuantity(current, delta, limit) { if (!Number.isInteger(delta)) return current; return Math.min(limit, Math.max(0, current + delta));}const cartSlice = createSlice({name:'cart',initialState:{ids:['pen','pad'],byId:{pen:{id:'pen',name:'Pen',priceCents:250,quantity:0,limit:5},pad:{id:'pad',name:'Pad',priceCents:400,quantity:0,limit:3}}},reducers:{ quantityChanged(state,action){ const {id,delta}=action.payload; if (!Object.hasOwn(state.byId,id)) return; const item=state.byId[id]; item.quantity=nextQuantity(item.quantity,delta,item.limit); }, cleared(state){for(const id of state.ids) state.byId[id].quantity=0;}}});const {quantityChanged,cleared}=cartSlice.actions;function makeStore(){return configureStore({reducer:{cart:cartSlice.reducer},devTools:false});}function Panel(){const action=quantityChanged({id:'pad',delta:1});const dispatch=useDispatch();const n=useSelector(s=>s.cart.byId.pad.quantity);return <section><pre>{JSON.stringify(action,null,2)}</pre><p>Pad quantity: {n}</p><button onClick={()=>dispatch(action)}>Apply action</button></section>;}export default function App(){const [store]=useState(makeStore);return <Provider store={store}><Panel /></Provider>;}The action has a type and payload that can be inspected. Keep state and ordinary actions composed of predictable plain values, using a string timestamp rather than a Date object when needed. Functions, promises, DOM nodes and class instances are usually inappropriate stored data. RTK’s development serializability and immutability checks can report mistakes; they do not prove data is safe to persist. Never place tokens or private records in a debug log. Do not disable checks just to hide a design problem.
Practice
Trace adding a pen six times, removing it seven times, and dispatching an unknown ID. Explain why changing a selected product object directly is not equivalent to changing an Immer draft.