0Pricing
Frontend Academy · Lesson

Redux Toolkit: createSlice and configureStore

Define state slices with createSlice, combine them in configureStore, and dispatch actions from React components using useDispatch and useSelector.

Redux Toolkit: createSlice and configureStore is a free Frontend Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Redux Toolkit?

Redux Toolkit (RTK) is the official, opinionated way to write Redux logic. It eliminates the boilerplate of plain Redux: no manual action type strings, no verbose reducers, no complex store setup.

Installing Redux Toolkit

Install both RTK and the React binding.

npm install @reduxjs/toolkit react-redux

createSlice — State + Reducer + Actions

createSlice creates a slice of state with its reducer and action creators in one call. Under the hood, it uses Immer for immutable updates.

import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: state => { state.value++; },     // Immer: mutate directly
    decrement: state => { state.value--; },
    reset: state => { state.value = 0; },
    incrementBy: (state, action) => { state.value += action.payload; }
  }
});

export const { increment, decrement, reset, incrementBy } = counterSlice.actions;
export default counterSlice.reducer;

configureStore — Assembling the Store

configureStore creates the Redux store with sensible defaults: Redux DevTools enabled, thunk middleware included.

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
import cartReducer from './cartSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
    cart: cartReducer,
  }
});

// TypeScript types:
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

Providing the Store

Wrap your app with <Provider store={store}> from react-redux.

import { Provider } from 'react-redux';
import { store } from './store';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <Provider store={store}>
    <App />
  </Provider>
);

useSelector — Reading State

useSelector(selector) reads from the store. It re-renders the component when the selected slice changes.

import { useSelector } from 'react-redux';
import type { RootState } from './store';

function Counter() {
  const count = useSelector((state: RootState) => state.counter.value);
  return <p>Count: {count}</p>;
}

useDispatch — Dispatching Actions

useDispatch() returns the store's dispatch function. Call it with an action creator to trigger a state change.

import { useDispatch } from 'react-redux';
import { increment, incrementBy } from './counterSlice';

function Controls() {
  const dispatch = useDispatch();
  return (
    <div>
      <button onClick={() => dispatch(increment())}>+1</button>
      <button onClick={() => dispatch(incrementBy(5))}>+5</button>
    </div>
  );
}

createAsyncThunk — Async Actions

RTK's createAsyncThunk handles async operations (API calls) and dispatches pending/fulfilled/rejected actions automatically.

import { createAsyncThunk } from '@reduxjs/toolkit';

export const fetchUser = createAsyncThunk(
  'user/fetchById',
  async (userId: string) => {
    const res = await fetch(`/api/users/${userId}`);
    return res.json(); // becomes action.payload on fulfilled
  }
);

// In slice:
extraReducers: (builder) => {
  builder
    .addCase(fetchUser.pending, state => { state.loading = true; })
    .addCase(fetchUser.fulfilled, (state, action) => {
      state.loading = false;
      state.user = action.payload;
    });
}

RTK Query — Data Fetching Built In

RTK Query (part of RTK) provides automatic data fetching, caching, and invalidation. Define API endpoints and get generated hooks.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (build) => ({
    getUsers: build.query<User[], void>({ query: () => 'users' }),
  })
});

// Generated hook:
const { data, isLoading, error } = api.useGetUsersQuery();

Immer in Reducers

RTK uses Immer internally, so slice reducers can mutate state directly. Immer detects mutations and produces a new immutable state object — you get the ergonomics of mutation with the safety of immutability.

Redux DevTools

Redux DevTools browser extension lets you inspect every dispatched action, the resulting state, and even time-travel: jump to any previous state. Invaluable for debugging complex state flows.

Quick Check

What does createSlice in Redux Toolkit generate automatically?

Recap: Redux Toolkit

createSlice combines reducer + actions in one definition. Immer lets you 'mutate' state safely. configureStore assembles reducers with DevTools + thunk. useSelector reads state. useDispatch dispatches actions. createAsyncThunk for async flows. RTK Query for full data fetching with caching.

Frequently asked questions

Is the “Redux Toolkit: createSlice and configureStore” lesson free?

Yes — the full text of “Redux Toolkit: createSlice and configureStore” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.

What will I learn in “Redux Toolkit: createSlice and configureStore”?

Define state slices with createSlice, combine them in configureStore, and dispatch actions from React components using useDispatch and useSelector. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Frontend Academy?

No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Redux Toolkit: createSlice and configureStore” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Frontend Academy lesson?

Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Redux Toolkit: createSlice and configureStore
  2. Zustand for Lightweight React State
  3. Pinia for Vue: defineStore and storeToRefs
  4. When to Use Global vs Local State
← Back to Frontend Academy