Skip to main content

Lesson 4 of 9

Redux Toolkit (RTK) Essentials

Redux Toolkit is the official, batteries-included way to use Redux. It eliminates the verbosity of classic Redux and provides createSlice (actions + reducer in one), createAsyncThunk (async actions with built-in loading states), and RTK Query (a full data-fetching solution).

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

createSlice, configureStore & createAsyncThunk

createSlice, configureStore & createAsyncThunk
import { createSlice, createAsyncThunk, configureStore, type PayloadAction } from '@reduxjs/toolkit';

// createAsyncThunk - handles pending/fulfilled/rejected automatically
export const fetchUsers = createAsyncThunk(
  'users/fetchAll',
  async (_, { rejectWithValue }) => {
    try {
      const response = await fetch('/api/users');
      if (!response.ok) throw new Error('Failed to fetch');
      return await response.json() as User[];
    } catch (err) {
      return rejectWithValue((err as Error).message);
    }
  }
);

// createSlice - generates actions and reducer together
const usersSlice = createSlice({
  name: 'users',
  initialState: {
    items: [] as User[],
    loading: false,
    error: null as string | null,
    selectedId: null as string | null,
  },
  reducers: {
    // Synchronous actions - Immer lets you "mutate" safely
    selectUser(state, action: PayloadAction<string>) {
      state.selectedId = action.payload;
    },
    deleteUser(state, action: PayloadAction<string>) {
      state.items = state.items.filter(u => u.id !== action.payload);
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchUsers.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchUsers.fulfilled, (state, action) => {
        state.loading = false;
        state.items = action.payload;
      })
      .addCase(fetchUsers.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { selectUser, deleteUser } = usersSlice.actions;

// configureStore - sets up Redux DevTools automatically
export const store = configureStore({
  reducer: {
    users: usersSlice.reducer,
    cart: cartSlice.reducer,
  },
});

// TypeScript - export typed hooks
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

// main.tsx - wrap with Provider
import { Provider } from 'react-redux';
<Provider store={store}><App /></Provider>

// Typed hooks - use these instead of raw useSelector/useDispatch
import { useDispatch, useSelector, type TypedUseSelectorHook } from 'react-redux';
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

// In a component
function UserList() {
  const dispatch = useAppDispatch();
  const { items, loading } = useAppSelector(state => state.users);

  useEffect(() => { dispatch(fetchUsers()); }, [dispatch]);

  if (loading) return <Spinner />;
  return <ul>{items.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}

Common Mistakes - Redux Toolkit

  • Using raw Redux instead of RTK - the old way (action creators, switch statements, thunks manually) requires 3x more code; always use RTK for new Redux code
  • Reselect for derived state - complex selectors should use `createSelector` from RTK/reselect for memoization; raw selectors in useAppSelector run on every state change
  • Storing non-serializable values in Redux - dates, class instances, functions, and React components can't be serialized; RTK throws a warning; store only plain JS values

Tip

Tip

Practice Redux Toolkit RTK Essentials in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for Redux Toolkit (RTK) Essentials

Practice Task

Note

Practice Task - (1) Write a working example of Redux Toolkit RTK Essentials from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Redux Toolkit RTK Essentials is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • Redux Toolkit is the official, batteries-included way to use Redux.
  • Using raw Redux instead of RTK - the old way (action creators, switch statements, thunks manually) requires 3x more code; always use RTK for new Redux code
  • Reselect for derived state - complex selectors should use `createSelector` from RTK/reselect for memoization; raw selectors in useAppSelector run on every state change
  • Storing non-serializable values in Redux - dates, class instances, functions, and React components can't be serialized; RTK throws a warning; store only plain JS values

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done