How to understand a Redux Toolkit codebase
Redux Toolkit organises global state into slices, each with its reducers and generated actions, combined into one store. Server data is often handled by RTK Query, which generates hooks per endpoint. Understanding a feature means finding its slice or API endpoint and the components that select from it.
How to tell it's Redux Toolkit
@reduxjs/toolkitandreact-reduxinpackage.jsonconfigureStore,createSliceandcreateApicalls- Typed hooks such as
useAppSelectoranduseAppDispatch
Where things usually live
- src/store.ts or app/store.ts
configureStorewith reducers and middleware.- src/features/<name>/<name>Slice.ts
- A slice: state, reducers, exported actions and selectors.
- src/services/api.ts
- RTK Query
createApiwith endpoints and cache tags. - src/hooks.ts
- Typed
useSelectoranduseDispatchwrappers.
Conventions, not rules. Real projects rename and move things, so confirm against the repository.
Where to start reading
- The store setup, to see every slice
- The slice for the feature
- The API slice, for server data
How a request moves through the code
- A component dispatches an action, such as
addItem(item), or calls an RTK Query hook. - Middleware runs: thunks, RTK Query and any custom middleware.
- The slice reducer updates state, written with mutating syntax that Immer makes immutable.
- Components re-render when the values their selectors return change.
- RTK Query caches responses and refetches when tags are invalidated by mutations.
Questions to ask about the repository
- List the slices and what state each one owns.
- Which components read the cart state, and which dispatch to it?
- Which RTK Query mutations invalidate which queries?
What trips people up
- Reducers look like they mutate state, but they only do so inside Immer; the same code elsewhere would be a bug.
- Selectors that build new objects re-render on every change unless memoised.