Model async thunks and middleware
Choose a thunk for a workflow
A thunk lets dispatch initiate work that can finish later. Redux Toolkit creates pending, fulfilled and rejected actions for an asynchronous operation, but your slice still decides how to represent those results. Use the async thunk for a workflow that needs Redux state and explicit transitions; prefer a query cache for ordinary repeated server reads. The inventory fixture below has no HTTP dependency. It resolves a known item to a quantity or returns a plain error record. Each example is an independent App.jsx for the RTK 2.x and React Redux 9.x lane with approved dependencies; none requires a real inventory service.
import React, {useState} from 'react';import {configureStore, createSlice, createAsyncThunk, createEntityAdapter, createSelector, createListenerMiddleware} from '@reduxjs/toolkit';import {Provider, useSelector, useDispatch} from 'react-redux';function stockFor(id){if(id==='lamp') return 4;if(id==='chair') return 2;return null;}const loadStock=createAsyncThunk('stock/load',async(id,{rejectWithValue})=>{ const amount=stockFor(id); return amount===null?rejectWithValue({code:'NOT_FOUND'}):{id,amount};});function isCurrent(currentId, incomingId){return currentId===incomingId;}const slice=createSlice({name:'stock',initialState:{status:'idle',requestId:null,record:null,error:null},reducers:{},extraReducers:builder=>builder .addCase(loadStock.pending,(s,a)=>{s.status='pending';s.requestId=a.meta.requestId;s.record=null;s.error=null;}) .addCase(loadStock.fulfilled,(s,a)=>{if(!isCurrent(s.requestId,a.meta.requestId))return;s.status='fulfilled';s.record=a.payload;s.requestId=null;}) .addCase(loadStock.rejected,(s,a)=>{if(!isCurrent(s.requestId,a.meta.requestId))return;s.status='rejected';s.error=a.payload?.code??a.error.message??'UNKNOWN';s.requestId=null;})});function makeStore(){return configureStore({reducer:{stock:slice.reducer},devTools:false});}function Panel(){const stock=useSelector(s=>s.stock);const dispatch=useDispatch();return <section><h2>Stock lookup</h2>{['lamp','chair','missing'].map(id=><button key={id} onClick={()=>dispatch(loadStock(id))}>Load {id}</button>)}<p role="status">{stock.status}</p>{stock.record&&<p>{stock.record.id}: {stock.record.amount}</p>}{stock.error&&<p role="alert">{stock.error}</p>}</section>;}export default function App(){const [store]=useState(makeStore);return <Provider store={store}><Panel/></Provider>;}Load lamp to see lamp: 4; load missing to see NOT_FOUND. Pending may be too brief to see with this immediate mock. The request ID guard accepts completion only for the most recently started lookup. This is a latest-request-wins policy for one display slot, not a general per-entity cache. A real slow request should also use the thunk signal if the transport supports it. Dispatch returns a promise for the final action; use .unwrap() when a caller needs rejection to throw. A dispatched thunk that fails does not automatically throw to the event handler. Test delayed A then B completion in reverse order with controlled promises.
Normalize shared entities
import React, {useState} from 'react';import {configureStore, createSlice, createAsyncThunk, createEntityAdapter, createSelector, createListenerMiddleware} from '@reduxjs/toolkit';import {Provider, useSelector, useDispatch} from 'react-redux';const adapter=createEntityAdapter();const slice=createSlice({name:'inventory',initialState:adapter.setAll(adapter.getInitialState(),[{id:'lamp',name:'Lamp',quantity:4},{id:'chair',name:'Chair',quantity:0}]),reducers:{restocked: (state,action)=>{const item=state.entities[action.payload];if(item) adapter.updateOne(state,{id:item.id,changes:{quantity:item.quantity+1}});}}});const selectors=adapter.getSelectors(s=>s.inventory);const selectAvailable=createSelector([selectors.selectAll],items=>items.filter(item=>item.quantity>0));function makeStore(){return configureStore({reducer:{inventory:slice.reducer},devTools:false});}function Panel(){const all=useSelector(selectors.selectAll);const available=useSelector(selectAvailable);const dispatch=useDispatch();return <section><p>Available kinds: {available.length}</p><ul>{all.map(item=><li key={item.id}>{item.name}: {item.quantity} <button onClick={()=>dispatch(slice.actions.restocked(item.id))}>Restock {item.name}</button></li>)}</ul></section>;}export default function App(){const [store]=useState(makeStore);return <Provider store={store}><Panel/></Provider>;}Initially one kind is available. Restock Chair to make two available. The adapter maintains ids and entities; selectAll creates a view of records, and createSelector can reuse a derived result while its inputs are unchanged. updateOne merges the supplied changes shallowly. Do not copy entity records into multiple independent state fields just to show filtered results. A memoized selector is not a storage layer or a guarantee of zero renders.
React to actions outside the reducer
import React, {useState} from 'react';import {configureStore, createSlice, createAsyncThunk, createEntityAdapter, createSelector, createListenerMiddleware} from '@reduxjs/toolkit';import {Provider, useSelector, useDispatch} from 'react-redux';const slice=createSlice({name:'inventory',initialState:{quantity:0,notice:''},reducers:{added:s=>{s.quantity++;},noticed:(s,a)=>{s.notice=a.payload;}}});function noticeFor(quantity){return quantity===0?'Empty':`${quantity} in stock`;}function makeStore(){const listener=createListenerMiddleware();listener.startListening({actionCreator:slice.actions.added,effect:(_,api)=>{api.dispatch(slice.actions.noticed(noticeFor(api.getState().inventory.quantity)));}});return configureStore({reducer:{inventory:slice.reducer},middleware:gdm=>gdm().prepend(listener.middleware),devTools:false});}function Panel(){const state=useSelector(s=>s.inventory);const dispatch=useDispatch();return <section><button onClick={()=>dispatch(slice.actions.added())}>Add item</button><p role="status">{state.notice||'Empty'}</p></section>;}export default function App(){const [store]=useState(makeStore);return <Provider store={store}><Panel/></Provider>;}Click Add item twice to see 2 in stock. The listener observes the added action and dispatches a different action; it does not subscribe to its own noticed action. Keep side effects outside reducers, register listeners once per store, and avoid loops. For long-running listener effects use explicit cancellation and cleanup. DevTools are disabled here to avoid accidental state exposure; disabling them is not a security boundary. Never store credentials or personal data merely for debugging.
Practice
Trace pending A, pending B, fulfilled B, rejected A. Explain why the display retains B and why a normalized collection is different from a request cache.