How to setup Redux ToolKit in React application
The Battle of state management
So, 2021 will be over in the next 6 months! What an amazing half year this was, wasn’t it?
Enough of this sarcasm. I think we all know the reality. I only turned this on because timing is really important for the topic this post will cover (as it might get change over time).
Let’s talk about the state as just we can be on the same page. Every interactive app involves responding to particular events, like when to open the sidebar, when the user clicks a button, and when to close the popup. Or someone sends a message, and it appears in a chat window. The app looks different than it did before, or it’s in a new mode when these events get responded with states. Now, state management is a broad term that combines how you store the states of your app and how you change and play with it without being worried about props drilling and complexing the codebase.
A first and important point to bring attention to is “Not all the apps required state management library or tool”, but as our app grows, it becomes necessary to apply Redux, MobX, Recoil, Hookstate, and the list is endless while we talk about state management. Personally, when I was brand new to this thing I probably have not used any state management thing for my to-do list app. But when you have a large example and a faster-growing app then it is good to put a thing into practice.
Let’s dig deeper to conclude how I started admiring RTK(Redux Toolkit)!
Redux has probably been the first react-based state management library, indeed it provides wonderful functionalities but its size, initial difficulties to make it friendly, and containing more action-reducer code approach than needed can make some people want to switch. And I was one of them.
RTK is build to address three common concerns:
- “Configuring a Redux store is too complicated”
- “I have to add a lot of packages to get Redux to do anything useful”
- “Redux requires too much boilerplate code”
Redux toolkit comes with several useful packages installed with it like Immer, Redux-Thunk, and Reselect. It makes life easier for React developers, allowing them to mutate state directly (Immer handles immutability) and applying middleware like Thunk (which handles async actions). It also uses Reselect, a simple “selector” library for Redux, to simplify reducer functions.
Major features provided by Redux Toolkit
The following API function is used by Redux Took Kit, which is an abstract of the existing Redux API function. These function does not change the flow of Redux but only streamline them in a more readable and manageable manner.
1. configureStore: Creates a Redux store instance like the original createStore from Redux, but accepts a named options object and sets up the Redux DevTools Extension automatically.
2. createAction: Accepts an action type string and returns an action creator function that uses that type.
3. createReducer: Accepts an initial state value and a lookup table of action types to reducer functions and creates a reducer that handles all action types.
4. createSlice: Accepts an initial state and a lookup table with reducer names and functions and automatically generates action creator functions, action type strings, and a reducer function.
There’s one speciality of createSlice, All the actions and reducers are in a simple place wherein a traditional redux application you need to manage every action and its corresponding action inside the reducer. when using createSlice you don’t need to use a switch to identify the action.
I really appreciate how it handles async Redux flows, let me give you some glimpse about it:
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
users: [],
loading: false,
error: null,
};
const GetUsers = createAsyncThunk(
"/users", async () => await axios.get(`https://jsonplaceholder.typicode.com/users`)
);
const userSlice = createSlice({
name: "user",
initialState: initialState,
extraReducers: {
[GetUsers.fulfilled]: (state, action) => {
state.users = action.payload.data;
state.loading = false;
},
[GetUsers.rejected]: (state, action) => {
state.users = [];
state.loading = false;
state.error = action.payload.errors;
},
},
});
export default userSlice.reduce
Let’s check how to use it,
import React, { useState } from "react";
import { createUser } from "../features/user/userSlice";
import { useSelector, useDispatch } from "react-redux";
const User = () => {
const dispatch = useDispatch();
const [user, setUser] = useState(initState);
const { users } = useSelector((state) => state.user)const CreateUser = () => {
dispatch(
createUser({
id: Math.random(),
name: user.name,
username: user.username,
})
);
}
return (
<table className="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Username</th>
<th scope="col">Option</th>
</tr>
</thead>
<tbody>
{
users?.map((row) => {
return (
<tr key={row.id}>
<td>{row.name}</td>
<td>{row.username}</td>
</tr>
);
})}
</tbody>
</table>
)}
Closing thoughts that wrap up our learning!
Based on my experience, Redux Toolkit is a great option to use when getting started with Redux. It simplifies the code and helps to manage the Redux state by reducing the boilerplate code.
Basically, I had set up a redux toolkit in one of the fastest-growing platforms, DhiWise, which is ProCode platform for building any kind of applications in NodeJS, Kotlin, ReactJS, Flutter, and IOS. I’ve seen marvelous changes in performance after setting up Redux Toolkit.
Thanks for reading!
Reference: