reactjs
/

Redux Toolkit (RTK) – The Modern Standard

Last Sync: Today

On this page

4
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

reactjs

Redux Toolkit (RTK) – The Modern Standard

Why Redux Toolkit?

Redux Toolkit (RTK) was created to solve three common complaints about Redux: 'Configuring a store is too complicated', 'I have to add a lot of packages to get Redux to do anything useful', and 'Redux requires too much boilerplate code'. RTK is now the official, recommended way to write Redux logic.

The Anatomy of a Slice

A 'Slice' is the collection of Redux reducer logic and actions for a single feature in your app. It uses Immer internally, which allows you to write 'mutative' code that is safely converted into immutable updates.

React JSXRead-only
1
import { createSlice } from '@reduxjs/toolkit';

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [], total: 0 },
  reducers: {
    addItem: (state, action) => {
      // Immer allows this 'push' safely!
      state.items.push(action.payload);
      state.total += action.payload.price;
    },
    removeItem: (state, action) => {
      state.items = state.items.filter(item => item.id !== action.payload);
    }
  }
});

export const { addItem, removeItem } = cartSlice.actions;
export default cartSlice.reducer;

Handling Async Logic with createAsyncThunk

For API calls, RTK provides createAsyncThunk. It generates promise lifecycle action types (pending, fulfilled, and rejected) which you can handle in the extraReducers field of your slice.

React JSXRead-only
1
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

export const fetchUsers = createAsyncThunk('users/fetchAll', async () => {
  const response = await fetch('https://api.example.com/users');
  return response.json();
});

const userSlice = createSlice({
  name: 'users',
  initialState: { data: [], status: 'idle' },
  extraReducers: (builder) => {
    builder
      .addCase(fetchUsers.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchUsers.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.data = action.payload;
      });
  }
});

RTK Query: The Future of Data Fetching

RTK Query is an optional addon included in the Redux Toolkit package. It is a powerful data fetching and caching tool designed to simplify loading data in a web application, eliminating the need to hand-write fetch logic or manage loading states manually.

FeatureStandard RTKRTK Query
Data ManagementManual (Slices/Thunks)Automated (Hooks)
CachingManual implementationAutomatic based on endpoints
Loading StatesManual (extraReducers)Provided automatically (isLoading)
BoilerplateModerateMinimal

Try it yourself

import React from 'react';
import { Provider, useSelector, useDispatch } from 'react-redux';
import { configureStore, createSlice } from '@reduxjs/toolkit';

// 1. Create Slice
const todoSlice = createSlice({
  name: 'todos',
  initialState: { list: [] },
  reducers: {
    addTodo: (state, action) => {
      state.list.push(action.payload);
    }
  }
});

// 2. Configure Store
const store = configureStore({ reducer: { todos: todoSlice.reducer } });
const { addTodo } = todoSlice.actions;

// 3. UI Component
function TodoApp() {
  const todos = useSelector(state => state.todos.list);
  const dispatch = useDispatch();

  const handleAdd = () => {
    const text = prompt('Enter Task:');
    if (text) dispatch(addTodo(text));
  };

  return (
    <div style={{ padding: '20px' }}>
      <h3>RTK Todo List</h3>
      <button onClick={handleAdd}>Add Item</button>
      <ul>
        {todos.map((todo, i) => <li key={i}>{todo}</li>)}
      </ul>
    </div>
  );
}

export default function App() {
  return (
    <Provider store={store}>
      <TodoApp />
    </Provider>
  );
}

Test Your Knowledge

Q1
of 3

Which RTK function is used to set up the Redux Store with middleware and DevTools?

A
createStore
B
configureStore
C
setupStore
D
initStore
Q2
of 3

What library does RTK use to allow 'mutative' logic in reducers?

A
Axios
B
Zod
C
Immer
D
Lodash
Q3
of 3

Where do you handle createAsyncThunk actions in a slice?

A
reducers
B
extraReducers
C
initialState
D
actions

Frequently Asked Questions

Can I use RTK with existing 'Vanilla' Redux?

Yes. RTK is fully compatible with existing reducers and actions. You can migrate your store to configureStore and move logic to slices one piece at a time.

Does RTK replace Redux DevTools?

No, it integrates with them perfectly. configureStore automatically enables the Redux DevTools extension for you.

What is Immer?

Immer is a library that RTK uses to allow you to write code that looks like you're mutating state (e.g., state.push()), but it creates a brand new immutable state object under the hood.

Previous

react redux intro

Next

react routing

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.