Read derived data with selectors
Derive totals from canonical state
A selector is a function that reads state and returns information. Store quantities and prices, not a second total that must be synchronized after every action. Here the number of items and total cents are computed from the normalized cart. The amounts are small integer cents; this avoids floating-point rounding in the sum. A real checkout still computes its authoritative price on the server.
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 selectTotalCents(state){return state.cart.ids.reduce((sum,id)=>{const item=state.cart.byId[id];return sum+item.quantity*item.priceCents;},0);}function selectItemCount(state){return state.cart.ids.reduce((sum,id)=>sum+state.cart.byId[id].quantity,0);}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 ids=useSelector(s=>s.cart.ids);const total=useSelector(selectTotalCents);const count=useSelector(selectItemCount);const dispatch=useDispatch();return <section><h2>Stationery cart</h2><ul>{ids.map(id=><Row key={id} id={id}/>)}</ul><p>Items: {count}</p><p>Total: ${(total/100).toFixed(2)}</p><button onClick={()=>dispatch(cleared())}>Clear cart</button></section>;}export default function App(){const [store]=useState(makeStore);return <Provider store={store}><Panel /></Provider>;}Initially the total is $0.00. Adding two pens and one pad produces three items and 900 cents ($9.00). The summary and row controls share one store. Each row selects a single record; the total selectors return primitives. useSelector uses strict reference equality by default, so a selector that creates a fresh object on every call can cause unnecessary updates. Multiple scalar selectors or a stable memoized result can help; shallowEqual is another explicit option. Do not promise exact render counts. Memoization and createSelector are treated in the next chapter.
Test selectors and independent store behavior
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 selectTotalCents(state){return state.cart.ids.reduce((sum,id)=>{const item=state.cart.byId[id];return sum+item.quantity*item.priceCents;},0);}function selectItemCount(state){return state.cart.ids.reduce((sum,id)=>sum+state.cart.byId[id].quantity,0);}function scenario(){const a=makeStore(),b=makeStore();a.dispatch(quantityChanged({id:'pen',delta:2}));a.dispatch(quantityChanged({id:'pad',delta:1}));return selectTotalCents(a.getState())===900 && selectItemCount(a.getState())===3 && selectTotalCents(b.getState())===0;}export default function App(){const [ok]=useState(scenario);return <p>{ok?'Store checks passed':'Unexpected cart result'}</p>;}This independent fixture is expected to report Store checks passed when the approved dependencies are installed. It exercises actual Redux only when executed. The local authoring checks extract the pure quantity and selector functions, not the store or Immer implementation. In integration tests, create a fresh store and Provider for each case; test disabled controls, clear behavior and independent instances. A pure selector test can use a small literal state without React.
Type the store boundary in TypeScript
import React, { useState } from 'react';import { configureStore, createSlice, type PayloadAction } from '@reduxjs/toolkit';import { Provider, useDispatch, useSelector } from 'react-redux';const slice=createSlice({name:'notes',initialState:{count:0},reducers:{added(state,action:PayloadAction<number>){state.count+=action.payload;}}});function makeStore(){return configureStore({reducer:{notes:slice.reducer},devTools:false});}type AppStore=ReturnType<typeof makeStore>;type RootState=ReturnType<AppStore['getState']>;type AppDispatch=AppStore['dispatch'];const useAppDispatch=useDispatch.withTypes<AppDispatch>();const useAppSelector=useSelector.withTypes<RootState>();function Panel(){const count=useAppSelector(s=>s.notes.count);const dispatch=useAppDispatch();return <button onClick={()=>dispatch(slice.actions.added(1))}>Notes: {count}</button>;}export default function App(){const [store]=useState(makeStore);return <Provider store={store}><Panel/></Provider>;}RootState is inferred from getState and AppDispatch from the configured store. withTypes gives the application reusable typed Hooks; it is available from React Redux 9.1. In a larger codebase put typed Hooks in a separate module to avoid runtime circular imports and use type-only imports. The button initially says Notes: 0 and increments by one. TypeScript helps catch mismatched action payloads at compile time but does not validate JSON or external inputs. This optional TSX example has only syntax transformation validation, not a dependency-resolved type check.
Practice
Construct a literal cart state containing two pens and one pad. Calculate both selectors, then change the pen quantity to zero using a copied record. Explain what belongs in Redux versus local state for a coupon text field.