Redux has a reputation for being verbose, difficult to configure and unnecessary for most applications. That reputation is understandable: early Redux examples often split actions, action types, reducers and constants across separate files, then added middleware and immutable update code by hand.
That is not the recommended way to write Redux today. The Redux maintainers now recommend Redux Toolkit as the standard approach. It provides store configuration, reducer creation, immutable update helpers, middleware defaults and developer tooling in a smaller and more consistent API. React applications normally use it alongside React-Redux, while RTK Query handles many server-data and caching concerns.
The important question is therefore not “How do I add Redux to this project?” It is “Which state deserves a shared, predictable model, and how should that model be organised?” Used selectively, Redux can make complex applications easier to reason about. Used indiscriminately, it can turn simple component state into a system that is harder to maintain than the original problem.
When Redux is a good fit
Redux is designed for global application state: data that is needed by multiple parts of an application, changes over time and benefits from an explicit update path. The official Redux fundamentals tutorial highlights large amounts of shared state, frequent updates, complex update logic and medium-to-large codebases as situations where Redux becomes more useful.
That does not mean every value should enter the store. A useful division is:
- Component state: temporary UI details such as whether a menu is open, the current value of an uncontrolled input or a hover state.
- URL state: filters, pagination, tabs and search terms that should survive a refresh or be shareable as a link.
- Server state: data fetched from an API, including loading, error, caching and invalidation concerns.
- Application state: shared client-side state such as an authenticated user’s preferences, a multi-step workflow or a shopping basket.
Redux is most valuable for the final category and for carefully selected parts of the others. RTK Query can be a better home for server state, while local component state is usually the simplest choice for ephemeral UI behaviour. Keeping those boundaries clear prevents the store from becoming a dumping ground.
Start with a modern store
The standard entry point is configureStore. It combines reducers, adds thunk middleware, enables Redux DevTools integration and includes development checks for accidental mutations and non-serialisable values. These defaults remove much of the setup that used to be written manually.
Install the two main packages in a React application:
npm install @reduxjs/toolkit react-redux
A small store can be configured like this:
import { configureStore } from '@reduxjs/toolkit'
import preferencesReducer from './features/preferences/preferencesSlice'
import basketReducer from './features/basket/basketSlice'
export const store = configureStore({
reducer: {
preferences: preferencesReducer,
basket: basketReducer
}
})
export const RootState = store.getState
export const AppDispatch = store.dispatch
For a TypeScript project, the type declarations should use ReturnType rather than assigning the store methods themselves. This gives components and thunks accurate types as the store grows:
import { configureStore } from '@reduxjs/toolkit'
import preferencesReducer from './features/preferences/preferencesSlice'
export const store = configureStore({
reducer: {
preferences: preferencesReducer
}
})
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
The application is then connected through the provider at the top of the React tree:
import { Provider } from 'react-redux'
import { store } from './app/store'
import { App } from './App'
export function Root() {
return (
<Provider store={store}>
<App />
</Provider>
)
}
Do not import the store directly into every component. React-Redux’s provider, useSelector and useDispatch hooks keep the connection explicit and make components easier to test. The Redux style guide recommends passing the store through the component tree and treating direct imports as an exception.
Organise code by feature, not by Redux primitive
A practical Redux codebase usually groups files by feature. A structure such as this keeps the state, reducers, selectors and tests that belong together in one place:
src/
app/
store.ts
hooks.ts
features/
basket/
basketSlice.ts
basketSelectors.ts
basketSlice.test.ts
preferences/
preferencesSlice.ts
services/
api.ts
This is more maintainable than separate top-level directories named actions, reducers and constants. A developer changing the basket feature can find its update logic and derived data together, without tracing several unrelated directories.
Use slices to describe a domain
A slice owns a part of the state tree and defines the events that can change it. createSlice generates action creators and action types from reducer definitions, while Immer allows concise update syntax that still produces immutable state updates.
Consider a basket that stores line items by product ID:
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
type BasketLine = {
productId: string
name: string
priceInPence: number
quantity: number
}
type BasketState = {
lines: Record<string, BasketLine>
}
const initialState: BasketState = {
lines: {}
}
const basketSlice = createSlice({
name: 'basket',
initialState,
reducers: {
itemAdded: (state, action: PayloadAction<BasketLine>) => {
const item = action.payload
const existing = state.lines[item.productId]
if (existing) {
existing.quantity += item.quantity
} else {
state.lines[item.productId] = item
}
},
itemRemoved: (state, action: PayloadAction<string>) => {
delete state.lines[action.payload]
},
quantityChanged: (
state,
action: PayloadAction<{ productId: string; quantity: number }>
) => {
const line = state.lines[action.payload.productId]
if (line && action.payload.quantity > 0) {
line.quantity = action.payload.quantity
}
}
}
})
export const { itemAdded, itemRemoved, quantityChanged } =
basketSlice.actions
export default basketSlice.reducer
The apparent mutation inside the reducers is intentional. Redux Toolkit uses Immer to translate those changes into immutable updates. That is safer and easier to read than manually copying nested objects and arrays, but it does not mean arbitrary component code may mutate selected state.
Action names should describe events rather than implementation commands. itemAdded communicates what happened. A name such as setBasketState hides the reason for the update and makes action history less useful during debugging. Event-focused actions also allow more than one reducer or middleware process to respond to the same event later.
Keep the state serialisable
Redux state and actions should normally contain plain serialisable values: strings, numbers, booleans, arrays, objects and null. Avoid putting class instances, DOM nodes, open sockets, promises, functions or browser-specific objects into the store.
Serialisable state works well with persistence, server rendering, logging, replay and the Redux DevTools. It also makes security boundaries clearer. Do not treat the store as a secret vault: anything placed in client-side state can be inspected by the user, browser extensions or debugging tools. Access tokens, refresh tokens and personal data require an explicit threat model and appropriate storage strategy rather than a casual Redux slice.
For authentication, keep the minimum client-visible information needed by the interface, such as the current user identity and permissions used for rendering. Enforce authorisation on the server as well. A hidden button or a Redux condition is not an access-control mechanism.
Derive values with selectors
State should contain the smallest useful source of truth. Values that can be calculated from existing state should generally be derived rather than stored separately. Duplicating totals, counts and filtered collections creates synchronisation problems.
A selector is a function that reads a value from the store:
import type { RootState } from '../../app/store'
export const selectBasketLines = (state: RootState) =>
Object.values(state.basket.lines)
export const selectBasketItemCount = (state: RootState) =>
Object.values(state.basket.lines)
.reduce((total, line) => total + line.quantity, 0)
export const selectBasketSubtotal = (state: RootState) =>
Object.values(state.basket.lines)
.reduce(
(total, line) => total + line.priceInPence * line.quantity,
0
)
Selectors provide a stable boundary between state shape and UI code. If the basket changes from an array to an entity map, components can continue using selectors without knowing about the internal representation.
Be aware that a selector returning a new array or object creates a new reference every time it runs. React-Redux compares selected values by reference by default, so a component may re-render even when the relevant data has not meaningfully changed. For expensive derived values, use memoised selectors with createSelector from Redux Toolkit:
import { createSelector } from '@reduxjs/toolkit'
import type { RootState } from '../../app/store'
const selectLines = (state: RootState) => state.basket.lines
export const selectBasketSubtotal = createSelector(
[selectLines],
(lines) =>
Object.values(lines).reduce(
(total, line) => total + line.priceInPence * line.quantity,
0
)
)
Memoisation is not a reason to wrap every selector automatically. Start with simple selectors, profile the application and memoise selectors that perform meaningful work or return derived references used by frequently rendered components.
Use RTK Query for server data
Fetching API data is one of the areas where older Redux applications accumulated the most repetitive code: request actions, loading flags, error actions, reducers, cache keys and invalidation logic.
RTK Query is the Redux Toolkit data-fetching and caching solution. It lets you define endpoints and generates hooks for React applications. The Redux style guide recommends it as the default approach for data fetching and caching in a Redux application.
A small API service might look like this:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
type Project = {
id: string
name: string
status: 'active' | 'archived'
}
export const projectsApi = createApi({
reducerPath: 'projectsApi',
baseQuery: fetchBaseQuery({
baseUrl: '/api/'
}),
tagTypes: ['Project'],
endpoints: (builder) => ({
getProjects: builder.query<Project[], void>({
query: () => 'projects',
providesTags: ['Project']
}),
archiveProject: builder.mutation<Project, string>({
query: (id) => ({
url: `projects/${id}/archive`,
method: 'POST'
}),
invalidatesTags: ['Project']
})
})
})
export const {
useGetProjectsQuery,
useArchiveProjectMutation
} = projectsApi
Register both the generated reducer and middleware:
import { configureStore } from '@reduxjs/toolkit'
import { projectsApi } from '../services/projectsApi'
export const store = configureStore({
reducer: {
[projectsApi.reducerPath]: projectsApi.reducer
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(projectsApi.middleware)
})
Then a component can focus on rendering states instead of manually coordinating request lifecycle actions:
import {
useGetProjectsQuery,
useArchiveProjectMutation
} from '../services/projectsApi'
export function ProjectList() {
const {
data: projects = [],
isLoading,
isFetching,
isError
} = useGetProjectsQuery()
const [archiveProject, { isLoading: isArchiving }] =
useArchiveProjectMutation()
if (isLoading) return <p>Loading projects…</p>
if (isError) return <p>Unable to load projects.</p>
return (
<section aria-busy={isFetching || isArchiving}>
{projects.map((project) => (
<button
key={project.id}
type="button"
onClick={() => archiveProject(project.id)}
>
Archive {project.name}
</button>
))}
</section>
)
}
RTK Query is not a replacement for every asynchronous workflow. A multi-step client-side process, file upload with custom progress handling or a workflow that coordinates several unrelated systems may be clearer as a thunk or listener middleware. Use the specialised tool that matches the problem rather than placing all asynchronous work in one pattern.
Understand dispatch, thunks and side effects
Reducers must remain predictable: given the same previous state and action, they should produce the same next state. Network requests, timers, analytics calls and browser APIs do not belong inside reducers.
For a one-off asynchronous workflow, createAsyncThunk can generate pending, fulfilled and rejected actions around an async function:
import { createAsyncThunk } from '@reduxjs/toolkit'
export const savePreferences = createAsyncThunk(
'preferences/save',
async (preferences: { theme: string }, thunkApi) => {
const response = await fetch('/api/preferences', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(preferences),
signal: thunkApi.signal
})
if (!response.ok) {
throw new Error('Could not save preferences')
}
return response.json()
}
)
Use the thunk lifecycle actions in the relevant slice, or handle the result in the component with the promise returned by dispatch. Keep error messages suitable for users at the UI boundary and avoid leaking server internals, credentials or sensitive request details into logs.
Performance practices that matter
Redux itself does not automatically make an application slow. Performance problems usually come from broad subscriptions, oversized state, repeated derivation or rendering too many components after a shared update.
- Select the smallest value a component needs instead of subscribing to an entire slice.
- Split large screens into components with focused selectors.
- Use stable primitive selections where possible.
- Memoise expensive derived data with
createSelector. - Normalise large collections when updates target individual entities.
- Keep large, short-lived editor values local if no other feature needs them.
- Measure with React profiling tools and Redux DevTools before adding complexity.
Do not solve every render concern with memoisation. A selector that is cheap and returns a primitive value is usually sufficient. Conversely, a selector that filters thousands of records on every store update deserves attention. Performance work should follow an observed bottleneck rather than a blanket rule.
Testing the boundaries
Redux code is comparatively testable when responsibilities are separated. Reducers can be tested as pure state transitions, selectors can be tested with representative state fixtures, and API behaviour can be tested with request mocks.
A reducer test should describe an event and assert the resulting state:
import reducer, { itemAdded } from './basketSlice'
test('adds a new basket item', () => {
const state = reducer(
{ lines: {} },
itemAdded({
productId: 'p-42',
name: 'Keyboard',
priceInPence: 8500,
quantity: 1
})
)
expect(state.lines['p-42'].quantity).toBe(1)
})
Also test business rules at the appropriate level. A reducer test can confirm that a quantity cannot become zero, but it cannot prove that the server will reject an unauthorised price change. Client-side validation improves usability; server-side validation remains authoritative.
Common mistakes to avoid
- Putting everything in Redux: local UI state often becomes harder to use when lifted into a global store.
- Manually reproducing RTK Query: multiple loading flags and cache reducers are a maintenance cost when the problem is ordinary API fetching.
- Storing derived values: duplicated totals and counts eventually disagree with their source data.
- Mutating state outside reducers: Immer only applies to the reducer logic it wraps.
- Using array indexes as entity identity: stable IDs make updates, caching and rendering more reliable.
- Importing the store everywhere: this hides dependencies and makes isolated tests more difficult.
- Disabling serialisability checks without a plan: suppressing warnings can conceal state-design problems.
- Trusting the client for security: Redux state controls presentation and workflow, not server authorisation.
A sensible adoption plan
If you are starting a new React project, use the official Redux Toolkit templates or add Redux Toolkit and React-Redux to the application. Define the state boundary before writing slices. Start with one feature that genuinely has shared or complex state, then add more only when the benefit is clear.
For an existing handwritten Redux codebase, migrate incrementally. Replace store creation with configureStore, convert related action and reducer files into a createSlice, move derived calculations into selectors and consider RTK Query for new API integrations. The official migration guidance explains how older patterns map to current APIs.
Redux is not a requirement for a serious application, and it should not be selected because a project has reached an arbitrary size. Its value appears when shared state has enough complexity that explicit events, predictable updates, inspection and tests reduce more risk than the architecture introduces.
The modern approach is deliberately pragmatic: keep simple state close to the component, keep server data in a purpose-built cache, keep global client state organised by feature and use Redux Toolkit to remove avoidable ceremony. That gives Redux a useful role in a contemporary frontend without bringing back the boilerplate that made it unfashionable.