Hack Frontend Community

Redux Toolkit

Redux Toolkit is official set of tools for efficient Redux development that simplifies most common Redux use cases, including store setup, creating reducers and immutable state updates.

Redux Toolkit Main Features

  • configureStore: Simplified store setup with built-in middleware
  • createSlice: Automatic creation of actions and reducers
  • createAsyncThunk: Simplified work with async operations
  • createEntityAdapter: Managing normalized data

Redux Toolkit Usage Example

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

// Creating slice
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;
    }
  }
});

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

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

Async Operations with createAsyncThunk

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

// Creating async action
export const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await fetch(`/api/users/${userId}`);
    return response.json();
  }
);

// Slice with async state handling
const userSlice = createSlice({
  name: 'user',
  initialState: {
    data: null,
    status: 'idle',
    error: null
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchUserById.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchUserById.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.data = action.payload;
      })
      .addCase(fetchUserById.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message;
      });
  }
});

Redux Toolkit Advantages:

Redux Toolkit significantly simplifies working with Redux, reduces boilerplate code and provides best practices out of the box.