React / 69
Redux DevTools, async thunks and RTK Query
Watch every action in DevTools, run async work in thunks, and let RTK Query fetch and cache server data so you don't hand-write it.
Redux DevTools
Install the Redux DevTools extension for Chrome, Edge or Firefox. configureStore connects to it automatically, so there's nothing to add to your code (pass devTools: false to turn it off).
- @@INIT
- cart/addItem
- cart/addItem
- cart/removeItem
- menu/fetch/pending
- menu/fetch/fulfilled
diff for cart/removeItem
cart › items− 1: { id: 2, name: "Burger", qty: 1 }payload: 2- Action log: every
dispatch, in order, with itstypeandpayload. - State and Diff tabs: the full store after any action, and exactly what that action changed.
- Time travel: jump back to any action to see the app as it was then.
- Dispatch: send an action by hand to test a reducer without building UI for it.
When something looks wrong, open DevTools first: either the right action was never dispatched, or the reducer handled it wrongly. The log tells you which.
Async logic with createAsyncThunk
A thunk is a function you dispatch instead of an action object. It can wait for things, then dispatch real actions. createAsyncThunk writes the boring parts for you: it dispatches pending, then fulfilled (with your return value) or rejected (if you throw).
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
export const fetchMenu = createAsyncThunk("menu/fetch", async () => {
const res = await fetch("https://dummyjson.com/recipes?limit=10");
if (!res.ok) throw new Error(`HTTP ${res.status}`); // fetch doesn't throw on 404/500
const data = await res.json();
return data.recipes; // becomes action.payload
});
const menuSlice = createSlice({
name: "menu",
initialState: { dishes: [], status: "idle" },
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchMenu.pending, (state) => { state.status = "loading"; })
.addCase(fetchMenu.fulfilled, (state, action) => {
state.status = "done";
state.dishes = action.payload;
})
.addCase(fetchMenu.rejected, (state) => { state.status = "error"; });
},
});
export default menuSlice.reducer;Start it from a component with useEffect(() => { dispatch(fetchMenu()); }, [dispatch]);. The thunk middleware that runs it is already included by configureStore.
extraReducers is how a slice responds to actions it didn't define, like this thunk's three actions, or another slice's logout. In Redux Toolkit 2 it only takes the builder callback; the old object form was removed.
RTK Query: let the library do the fetching
The slice above is a lot of code for "load a list". Most apps fetch many lists, and also need caching, refetching and de-duplicated requests. RTK Query (included in @reduxjs/toolkit) generates all of it:
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
export const menuApi = createApi({
reducerPath: "menuApi",
baseQuery: fetchBaseQuery({ baseUrl: "https://dummyjson.com/" }),
endpoints: (builder) => ({
getRecipes: builder.query({ query: () => "recipes?limit=10" }),
}),
});
export const { useGetRecipesQuery } = menuApi;Register it in the store, then use the generated hook:
export const store = configureStore({
reducer: { cart: cartReducer, [menuApi.reducerPath]: menuApi.reducer },
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(menuApi.middleware),
});
// in a component:
// const { data, isLoading, error } = useGetRecipesQuery();Rule of thumb: client state (the cart, UI choices) goes in slices; server state (anything you fetch) goes in RTK Query.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
