Setting up State Management (Redux) for React application
Redux — predictable state container with unidirectional data flow. Single global store, pure reducer functions, explicit action objects. For apps with complex business logic split across many components, Redux gives full control over how and when state changes.
We setup Redux with modern stack: Redux Toolkit to eliminate boilerplate, RTK Query for server state, Redux DevTools for debugging.
When Redux is justified
Redux isn't for every project. Signs it fits:
- State shared between 5+ unrelated components
- Complex state transitions with business rules
- Need full change history (time-travel debugging)
- Multiple data sources updating one state
- 5+ developer team needing predictability
For local component state — useState. For server data — TanStack Query or RTK Query. Redux only for global client state.
Store structure
src/
store/
index.ts # Store configuration
hooks.ts # Typed useAppDispatch, useAppSelector
slices/
authSlice.ts
cartSlice.ts
uiSlice.ts
api/
productsApi.ts # RTK Query endpoints
// store/index.ts
import { configureStore } from '@reduxjs/toolkit';
import { authSlice } from './slices/authSlice';
import { cartSlice } from './slices/cartSlice';
import { uiSlice } from './slices/uiSlice';
import { productsApi } from './api/productsApi';
export const store = configureStore({
reducer: {
auth: authSlice.reducer,
cart: cartSlice.reducer,
ui: uiSlice.reducer,
[productsApi.reducerPath]: productsApi.reducer,
},
middleware: (getDefault) =>
getDefault().concat(productsApi.middleware),
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
// store/hooks.ts — typed hooks
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './index';
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
export const useAppSelector = useSelector.withTypes<RootState>();
Slice with business logic
// store/slices/cartSlice.ts
import { createSlice, createSelector, type PayloadAction } from '@reduxjs/toolkit';
interface CartItem {
id: string;
name: string;
price: number;
qty: number;
image: string;
}
interface CartState {
items: CartItem[];
coupon: string | null;
couponDiscount: number;
}
const initialState: CartState = {
items: [],
coupon: null,
couponDiscount: 0,
};
export const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
addItem(state, action: PayloadAction<Omit<CartItem, 'qty'>>) {
const existing = state.items.find(i => i.id === action.payload.id);
if (existing) {
existing.qty += 1;
} else {
state.items.push({ ...action.payload, qty: 1 });
}
},
removeItem(state, action: PayloadAction<string>) {
state.items = state.items.filter(i => i.id !== action.payload);
},
updateQty(state, action: PayloadAction<{ id: string; qty: number }>) {
const item = state.items.find(i => i.id === action.payload.id);
if (item) {
item.qty = Math.max(1, action.payload.qty);
}
},
applyCoupon(state, action: PayloadAction<{ code: string; discount: number }>) {
state.coupon = action.payload.code;
state.couponDiscount = action.payload.discount;
},
clearCart(state) {
state.items = [];
state.coupon = null;
state.couponDiscount = 0;
},
},
});
// Memoized selectors
export const selectCartItems = (state: RootState) => state.cart.items;
export const selectCartTotal = createSelector(
selectCartItems,
(state: RootState) => state.cart.couponDiscount,
(items, discount) => {
const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0);
return subtotal * (1 - discount / 100);
}
);
export const selectCartCount = createSelector(
selectCartItems,
items => items.reduce((sum, item) => sum + item.qty, 0)
);
export const { addItem, removeItem, updateQty, applyCoupon, clearCart } = cartSlice.actions;
RTK Query for server state
// store/api/productsApi.ts
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const productsApi = createApi({
reducerPath: 'productsApi',
baseQuery: fetchBaseQuery({
baseUrl: '/api',
prepareHeaders: (headers, { getState }) => {
const token = (getState() as RootState).auth.token;
if (token) headers.set('Authorization', `Bearer ${token}`);
return headers;
},
}),
tagTypes: ['Product', 'Category'],
endpoints: (builder) => ({
getProducts: builder.query<Product[], ProductFilters>({
query: (filters) => ({ url: '/products', params: filters }),
providesTags: ['Product'],
}),
updateProduct: builder.mutation<Product, Partial<Product> & { id: string }>({
query: ({ id, ...body }) => ({ url: `/products/${id}`, method: 'PUT', body }),
invalidatesTags: ['Product'],
}),
}),
});
export const { useGetProductsQuery, useUpdateProductMutation } = productsApi;
Usage in components
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { addItem, selectCartCount } from '@/store/slices/cartSlice';
import { useGetProductsQuery } from '@/store/api/productsApi';
function ProductCard({ productId }: { productId: string }) {
const dispatch = useAppDispatch();
const cartCount = useAppSelector(selectCartCount);
const { data: product, isLoading } = useGetProductsQuery({ id: productId });
if (isLoading) return <Skeleton />;
return (
<div>
<h3>{product.name}</h3>
<button onClick={() => dispatch(addItem(product))}>
Add to cart ({cartCount})
</button>
</div>
);
}
Redux DevTools and debugging
Redux DevTools Extension enables:
- View all actions history
- Jump to any previous state (time-travel)
- Export/import state to reproduce bugs
// store/index.ts — additional DevTools config
configureStore({
...
devTools: process.env.NODE_ENV !== 'production' && {
name: 'MyApp',
trace: true, // Trace action calls
traceLimit: 25,
},
});
Implementation timeline
- Week 1: store setup, slices for main domains, typed hooks
- Week 2: RTK Query endpoints, integration with components
- Week 3: memoized selectors, rerender optimization (React.memo + reselect), reducer tests
- Week 4: state architecture documentation, code review, Redux DevTools in dev







