Redux toolkit in Detail

Redux Toolkit is the official, recommended way to write Redux logic. It is designed to simplify the process of setting up a Redux store, writing reducers, and handling complex logic such as middleware and side effects. This guide will cover the core features of Redux Toolkit, providing you with the knowledge to build scalable and maintainable applications.

Getting Started with Redux Toolkit

Installation

To get started with Redux Toolkit, you'll need to install it along with React-Redux:

npm install @reduxjs/toolkit react-redux

Setting Up the Store

The first step in using Redux Toolkit is to configure your store. The configureStore function from Redux Toolkit simplifies this process by providing sensible defaults and automatically including important middleware like Redux Thunk.

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './features/counter/counterSlice';

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

export default store;

Core Concepts

Slices

A slice is a collection of Redux reducer logic and actions for a single feature of your application. A slice reducer manages the state for a feature.

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

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
  },
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  },
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

export default counterSlice.reducer;

Store Configuration

configureStore is a wrapper around the traditional Redux createStore function that simplifies the setup by accepting a configuration object.

const store = configureStore({
  reducer: {
    counter: counterSlice.reducer,
  },
});

Reducers and Actions

Reducers and actions in Redux Toolkit are tightly coupled. The createSlice function generates action creators and action types based on the reducer functions you provide.

// Actions
store.dispatch(increment());
store.dispatch(decrement());
store.dispatch(incrementByAmount(5));

// State
console.log(store.getState().counter.value); // Outputs the current state

Advanced Features

Async Logic and Thunks

Redux Toolkit includes createAsyncThunk, which handles the standard Redux patterns for loading state, including dispatching lifecycle actions based on promise statuses.

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

export const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await fetch(`/fakeApi/user/${userId}`);
    return response.data;
  }
);

Middleware

Middleware in Redux Toolkit can be added during store configuration. By default, configureStore adds redux-thunk.

const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(customMiddleware),
});

RTK Query

RTK Query is a powerful data fetching and caching tool included with Redux Toolkit. It is designed to simplify data fetching logic and provide a more powerful way to manage server state.

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

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/fakeApi' }),
  endpoints: (builder) => ({
    getUserById: builder.query({
      query: (id) => `user/${id}`,
    }),
  }),
});

export const { useGetUserByIdQuery } = api;

Best Practices

  1. Use Slices for Each Feature: Break down your state and logic into manageable slices.

  2. Leverage createAsyncThunk: Handle async logic and side effects with thunks to keep your components clean.

  3. Organize Code by Feature: Group related code together to make it easier to navigate and maintain.

  4. Keep Middleware and Enhancers Declarative: Use configureStore to add middleware and store enhancers declaratively.

Conclusion

Redux Toolkit significantly reduces the boilerplate associated with Redux, making it easier to manage and scale applications. By understanding and leveraging its core and advanced features, you can write cleaner, more maintainable Redux code. Happy coding!


This guide provides an overview of the most important aspects of Redux Toolkit. For more detailed information, refer to the official Redux Toolkit documentation.

Last updated