Skip to main content

Lesson 4 of 9

Redux Toolkit - When Your Team Needs It

Redux Toolkit (RTK) is the official, opinionated Redux package that eliminates most Redux boilerplate. It's the right choice for large teams that need strict, predictable state transitions, time-travel debugging, and RTK Query for API caching.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Installation

Installation
npm install @reduxjs/toolkit react-redux

Redux Toolkit Store Setup

Redux Toolkit Store Setup
import { configureStore, createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';

// ---- Notifications Slice ----
interface Notification { id: string; message: string; type: 'info' | 'success' | 'error'; read: boolean; }
interface NotifState { items: Notification[]; loading: boolean; error: string | null; }

// Async thunk - handles loading/success/rejected automatically
export const fetchNotifications = createAsyncThunk(
  'notifications/fetch',
  async (userId: string) => {
    const res = await fetch(`/api/users/${userId}/notifications`);
    if (!res.ok) throw new Error('Failed to fetch notifications');
    return (await res.json()) as Notification[];
  }
);

const notifSlice = createSlice({
  name: 'notifications',
  initialState: { items: [], loading: false, error: null } as NotifState,
  reducers: {
    markRead: (state, action: PayloadAction<string>) => {
      const notif = state.items.find(n => n.id === action.payload);
      if (notif) notif.done = true; // Immer allows mutation syntax
    },
    markAllRead: (state) => { state.items.forEach(n => n.read = true); },
    dismiss: (state, action: PayloadAction<string>) => {
      state.items = state.items.filter(n => n.id !== action.payload);
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchNotifications.pending, (state) => { state.loading = true; state.error = null; })
      .addCase(fetchNotifications.fulfilled, (state, action) => {
        state.loading = false;
        state.items = action.payload;
      })
      .addCase(fetchNotifications.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message ?? 'Unknown error';
      });
  },
});

export const { markRead, markAllRead, dismiss } = notifSlice.actions;

// ---- Store ----
export const store = configureStore({
  reducer: {
    notifications: notifSlice.reducer,
    // Add more slices here
  },
});

// ---- Typed hooks (use these everywhere, not raw useDispatch/useSelector) ----
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

// ---- Provider setup (App.tsx) ----
// import { Provider } from 'react-redux';
// <Provider store={store}><App /></Provider>

// ---- Screen usage ----
function NotificationBell() {
  const unread = useAppSelector(state =>
    state.notifications.items.filter(n => !n.read).length
  );
  const dispatch = useAppDispatch();

  useEffect(() => {
    dispatch(fetchNotifications('me'));
  }, [dispatch]);

  return <Text>๐Ÿ”” {unread > 0 ? unread : ''}</Text>;
}

Tip

Tip

Practice Redux Toolkit When Your Team Needs It in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Enterprise state management with Redux slices, async thunks, and selectors

Practice Task

Note

Practice Task - (1) Write a working example of Redux Toolkit When Your Team Needs It 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 When Your Team Needs It is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/9 done