Sub topic 3
Handling Related State with Redux Toolkit
Assume you know React components, JavaScript modules, pure functions, and basic Redux Toolkit slices. This chapter connects slices to asynchronous work, caching, middleware, debugging, and tests.
Handling actions from other slices
A slice can respond to actions created elsewhere with extraReducers. This is useful when one event changes several parts of the store.
const postsSlice = createSlice({
name: 'posts',
initialState: { items: [], status: 'idle' },
reducers: {},
extraReducers: (builder) => {
builder.addCase(userLoggedOut, (state) => {
state.items = []
state.status = 'idle'
})
},
})extraReducers does not create new action creators. It only adds handlers for existing actions.
Async logic and server data
createAsyncThunk dispatches pending, fulfilled, and rejected actions around a promise. A slice can handle those lifecycle actions with extraReducers.
export const fetchTodos = createAsyncThunk(
'todos/fetchTodos',
async () => {
const response = await fetch('/api/todos')
if (!response.ok) throw new Error('Request failed')
return response.json()
}
)For server data, prefer RTK Query when possible. An API slice defines endpoints and generates hooks that fetch, cache, track loading states, and reuse results.
const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (build) => ({
getTodos: build.query({ query: () => 'todos' }),
}),
})Add both api.reducer and api.middleware to the store.
Collections, middleware, and debugging
createEntityAdapter stores records by ID and supplies reducers and selectors. It helps avoid repeated searches through large collections.
Middleware runs between dispatch and the reducer. Listener middleware can react to actions and run controlled side effects, such as starting a task after login. Keep side effects there instead of inside reducers.
Redux DevTools shows dispatched actions, state snapshots, and the action that caused a change. Use it to verify payloads and find unexpected updates.
Testing
Test reducers with an initial state and an action. Test selectors with a representative root state. For connected components, render them with a real test store or a small configured store, then interact with the UI and assert visible behavior.
> [!tip] > Test state transitions and user-visible results. Avoid testing Redux internals that the component does not expose.
Exercise
Which tool is usually the best fit for fetching, caching, and reusing server data?
Show answer
RTK Query, because its endpoints and generated hooks manage the request lifecycle and cache.