Redux Toolkit
Redux Toolkit (RTK) is the official way to write Redux: one store for shared app state, slices that create actions and reducers together, Immer for safe "mutating" code, createAsyncThunk for API calls and typed hooks for TypeScript.
46.1 Why is it used?
- Classic Redux reducers must never mutate state; React-Redux compares references to decide whether to update the UI.
- The reducer below pushes into state and returns the same object, so next === init is true and the UI never updates.
- Avoiding that by hand meant spread copies, separate action types and lots of boilerplate. RTK removes it.
const init = { items: [] }; function cartReducer(state = init, action) { switch (action.type) { case "cart/add": state.items.push(action.payload); return state; default: return state; }} const next = cartReducer(init, { type: "cart/add", payload: "Shirt" });console.log(next === init);> true- Step 1
1.Reducer mutates state.items.push(...)
- Step 2
2.Returns the same object
- Step 3
3.Same reference: React-Redux sees no change
- Step 4
4.UI never updates
- Step 5
5.Classic fix: spread copies + boilerplate; RTK fix: Immer
46.2 The Redux flow
- Step 1
1.Component: dispatch(action) e.g. { type: "cart/add" }
- Step 2
2.Reducer: current state + action = new state
- Step 3
3.Store saves the whole app state in one place
- Step 4
4.Components that select this data re-render
One-way data flow
46.3 createSlice: the cart slice
- createSlice gets a name ("cart"), initialState and reducers.
- add(state, action: PayloadAction<string>) pushes the payload into items.
- It looks like mutation but is safe: Immer turns the changes on a draft into a new immutable state.
- The slice exports the action creators (cartSlice.actions) and the reducer.
npm install @reduxjs/toolkit react-reduximport { createSlice, type PayloadAction } from "@reduxjs/toolkit"; const cartSlice = createSlice({ name: "cart", initialState: { items: [] as string[] }, reducers: { add(state, action: PayloadAction<string>) { state.items.push(action.payload); }, },});export const { add } = cartSlice.actions;export default cartSlice.reducer;46.4 configureStore and types
- configureStore takes a reducer object: cart and products slices.
- It turns on Redux DevTools and catches accidental mutations in development.
- RootState and AppDispatch come from the store itself, so adding a slice updates the types automatically.
- Wrap the app root once in <Provider store={store}>.
import { configureStore } from "@reduxjs/toolkit";import cartReducer from "./cartSlice";import productsReducer from "./productsSlice"; export const store = configureStore({ reducer: { cart: cartReducer, products: productsReducer, },});export type RootState = ReturnType<typeof store.getState>;export type AppDispatch = typeof store.dispatch;46.5 Typed hooks
- useAppDispatch = useDispatch.withTypes<AppDispatch>(); useAppSelector = useSelector.withTypes<RootState>().
- No repeating the state type in components, and dispatching thunks stays typed.
import { useDispatch, useSelector } from "react-redux";import type { AppDispatch, RootState } from "./store"; export const useAppDispatch = useDispatch.withTypes<AppDispatch>();export const useAppSelector = useSelector.withTypes<RootState>();46.6 Using it in a component
- useAppSelector selects only s.cart.items.length (with autocomplete on s).
- dispatch(add("Shirt")) runs the reducer; the button goes from Cart: 0 to Cart: 1.
import { useAppDispatch, useAppSelector } from "./hooks";import { add } from "./cartSlice"; export default function Cart() { const count = useAppSelector( (s) => s.cart.items.length); const dispatch = useAppDispatch(); const onAdd = () => dispatch(add("Shirt")); return ( <button onClick={onAdd}> Cart: {count} </button> );}-- initial --[button] Cart: 0 -- after click --[button] Cart: 146.7 createAsyncThunk: API calls
- Reducers are pure and synchronous, so you cannot fetch inside them.
- createAsyncThunk("products/load", async fn) wraps the API call; throw on !res.ok.
- Dispatching it sends pending, then fulfilled with the data, or rejected on error.
import { createAsyncThunk } from "@reduxjs/toolkit"; export const loadProducts = createAsyncThunk( "products/load", async () => { const res = await fetch("/api/products"); if (!res.ok) throw new Error("Failed"); return (await res.json()) as string[]; });-- request in flight --> products/load/pending -- data arrived --> products/load/pending> products/load/fulfilled46.8 extraReducers: loading and data
- Thunk actions are not the slice's own reducers, so handle them with the builder in extraReducers.
- pending sets status "loading"; fulfilled sets status "done" and saves list = a.payload; rejected sets "failed".
- The component reads status to show a loader or an error.
const productsSlice = createSlice({ name: "products", initialState, reducers: {}, extraReducers: (b) => { b.addCase(loadProducts.pending, (s) => { s.status = "loading"; }); b.addCase(loadProducts.fulfilled, (s, a) => { s.status = "done"; s.list = a.payload; }); },});- Step 1
1.Component dispatches loadProducts()
- Step 2
2.products/load/pending: status = "loading"
- Step 3
3.fetch("/api/products") runs
- Step 4
4.Success: products/load/fulfilled, list = payload
- Step 5
5.Error: products/load/rejected, status = "failed"
46.9 Checkpoint: state = { items: [] }
- A clear reducer that assigns state = { items: [] } does nothing: state is just a local variable, the Immer draft is unchanged.
- Correct: state.items = [] or return { items: [] }.
clear(state) { state = { items: [] };}, store.dispatch(add("Shirt"));store.dispatch(add("Shoes"));store.dispatch(clear());console.log(store.getState().cart.items);> [ 'Shirt', 'Shoes' ]46.10 Comparison: classic Redux vs Redux Toolkit
| Point | Classic Redux | Redux Toolkit |
|---|---|---|
| Store | createStore (legacy) + manual DevTools setup | configureStore, DevTools and mutation checks built in |
| Actions | Separate action type constants and creators | Generated by createSlice |
| Immutable updates | Spread copies by hand | Mutable-style code on an Immer draft |
| Async | Write thunk middleware logic yourself | createAsyncThunk: pending / fulfilled / rejected |
| TypeScript | Type everything manually | RootState, AppDispatch, withTypes hooks |
46.11 Common mistakes
- Selecting the whole state: the component re-renders on every action (even products loading) and React-Redux warns in development.
- Select only the small value you need; useSelector re-renders only when that value changes.
- Reassigning state inside a reducer instead of mutating a field or returning a new object.
- Myth: Redux means boilerplate and every state belongs in it. Keep form inputs and modals local; use TanStack Query for server data.
const state = useAppSelector((s) => s);const count = state.cart.items.length;const count = useAppSelector( (s) => s.cart.items.length);46.12 Best practices
- configureStore + createSlice, not the legacy createStore.
- One slice per feature (cart, user, products).
- Typed hooks (useAppSelector, useAppDispatch) in components.
- Only serializable data in the store: plain objects and arrays, no functions or class instances.
46.13 Interview tips
- RTK is the official way to write Redux: configureStore, createSlice, createAsyncThunk.
- createSlice builds actions and reducer together; Immer lets you write mutable-style code while state stays immutable.
- A thunk dispatches pending, fulfilled and rejected; handle them in extraReducers.
- Use typed hooks and select minimal slices of state to avoid extra re-renders.