×
iFour Logo

A step-by-step guide on using Redux Toolkit with React

iFour Team - August 26, 2022

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

A step-by-step guide on using Redux Toolkit with React

Introduction

Redux is more adaptable and popular among developers. In fact, when it comes to state management libraries, Redux appears to be the #1 option among front-end developers.

When developers work on a large project employing the most popular frameworks Angular, React, or Vue, then state management library is a key factor they deal with.

Several barriers persist while using Redux, which the Redux js toolkit attempts to address. As a result, the Redux team explicitly supports using this toolkit to eliminate issues. Now is the time for companies to prioritize this area of bespoke software development.

How Redux works?

Redux assists you in handling global state of your application. It effectively learns the app logic behavior in response to modifications made. The figure below depicts the Redux process of your application.

inner-content01
Figure 1 Redux Workflow
The main takeaway:
  1. A user interacts with the view to initiate an action event.
  2. Reducer receives the action from the dispatch event and updates the state accordingly.
  3. When the state is updated in the store the changes are modified via the subscription method and View updates its UI accordingly.

To understand how redux works, it’s essential to learn three components of redux flow which are Action, Reducer, and store.

I. Actions
  • Actions are plain JavaScript objects with the required simple string property type and can include a custom property to update the state.
  • Actions are not accountable for any state modifications, they merely describe what happens with the state.
II. Reducer
  • Reducer is a pure function.
  • It takes the current value of the state and updates it according to dispatch action.
III. Store
  • A store is a state container that holds the app’s state.
  • It manages all states and their updates effectively.
  • Redux applications have only one store to manage the state.

Planning to Hire ReactJS developer? Your search ends here.

Why Redux Toolkit over Redux?

Redux patterns make states predictable, scalable, and easy to maintain due to the precise rule of how each unit in the redux flow should behave and work.

However Redux comes with a few challenges:

  • A developer has to write too much code to configure a store
  • Too much code makes it hard to understand and less clean
  • Too many packages need to be installed
  • Writing reducers become more complex in Redux

To overcome these challenges, the Redux team introduced Redux Toolkit which enables you write redux logic efficiently. Redux toolkit includes core redux packages with simple & clean redux code.

How to use Redux Toolkit?

Step 1: Install Packages

Install the required packages first in order to use Redux Toolkit and React-redux in your React application.

npm install @reduxjs/toolkit react-redux
Step 2: Create reducer and actions

In traditional redux, you may write actions and reducer functions separately just as shown below:

Actions
const INCREMENT = "INCREMENT";
const DECREMENT = "DECREMENT";
const RESET = "RESET";

export { INCREMENT, DECREMENT, RESET };

Reducer
const intialState = {
  count: 0,
};

const counterReducer = (state = intialState, action) => {
  switch (action.type) {
    case "INCREMENT": {
      return {
        count: state.count + 1,
      };
    }
    case "DECREMENT": {
      return {
        count: state.count - 1,
      };
    }
    case "RESET": {
      return {
        count: 0,
      };
    }
    default:
      return state;
  }
};

export default counterReducer;


By using the Redux toolkit and createSlice, you may write better code with fewer lines.

Now, create a counterSlice.js file in the src/slice/ directory. The counterSlice file will look like this:

counterSlice.js

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

const counterSlice = createSlice({
  name: "counter",
  initialState: {
    count: 0,
  },
  reducers: {
    incrementCount(state) {
      state.count = state.count + 1;
    },
    decrementCount(state) {
      state.count = state.count - 1;
    },
    resetCount(state) {
      state.count = 0;
    },
  },
});

export default counterSlice;
export const counterSliceAction = counterSlice.actions;

As you can see, the code is considerably better and understandable with less lines. It is not necessary to use switch case statements to manage actions with matching reducers. It also supported directly-assigning value to the state rather than returning the new value when updating the state.

Step 3: Create and initialize the store

Next, create a store.js file in the src directory of the project. The store holds the state of our application.

To create a store, first you should import the configureStore from the redux-toolkit package.

Here the createStore in redux is replaced by configureStore. configureStore not only creates the store but also accepts reducer functions as an argument and automatically installs the Redux DevTools extension for debugging.


import counterSlice from "./slices/counterSlice";
import { configureStore } from "@reduxjs/toolkit";

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

export default store;

Here counterSlice reducer is imported from counterSlice.js and passed it to configureStore.

Step 4: Provide the store to React application

Once done with creating the store, import the React-redux Provider and pass the store as a prop. This allows you to access the store from any component of your React application.


import React from "react";
import ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import App from "./App";
import store from "./store";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  
    
      
    
  
);

Step 5: Dispatch actions from the react component

Now, create a Counter.js component in the src directory. And import the useSelector and useDispatch hook from the react-redux.

  • Note: useSelector hook is used to read data from the store & useDispatch hook is used to dispatch or trigger an event.

Also, you need to import actions from counterSlice.js to trigger an event.

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import {userSliceAction}  from "./slices/counterSlice"


Now initialize the useDispatch and useSelector hook in a counter component. Here you may get the value of count using the useSelector hook and dispatch the event when the user clicks the increment, decrement, and reset button.

When a user hit one of these buttons, an event is fired in the counterSlice reducer based on the action's count update value.


const Counter = () => {
  const count = useSelector((state) => state.count.count);
  const dispatch = useDispatch();

  return (
    &lt;&gt;<div classname="container"><h3>Counter App Using Redux Toolkit</h3>
<h1>{count}</h1>
<div classname="btn-container"><button onclick="{()"> dispatch(counterSliceAction.incrementCount())}&gt;
            Increment</button><button onclick="{()"> dispatch(counterSliceAction.decrementCount())}&gt;
            Decrement</button><button onclick="{()"> dispatch(counterSliceAction.resetCount())}&gt;
            Reset</button></div></div>
    &lt;/&gt;
  );
};

export default Counter;



Here is the final output of your Redux toolkit-powered counter react application.

inner-content01
Figure 2 Counter application using Redux Toolkit

That’s it for this tutorial, stay tuned with iFour Technolab for more interesting and informative blogs.

Conclusion

Redux enables developers to write simpler, more legible code while maintaining the redux in the appropriate flow and pattern. For beginners and developers, the Redux toolkit is a great option to reduce the amount of boilerplate code in Redux.

In this blog, we discussed how Redux works, its limitations, and why you should use Redux Toolkit instead of Redux. We also learnt how to utilize the redux toolkit in a React project and develop redux code in a single file, including reducers and actions.

A step-by-step guide on using Redux Toolkit with React Table of Content 1.Introduction 2.How Redux works? 3.Why Redux Toolkit over Redux? 4.How to use Redux Toolkit? 5.Conclusion Introduction Redux is more adaptable and popular among developers. In fact, when it comes to state management libraries, Redux appears to be the #1 option among front-end developers. When developers work on a large project employing the most popular frameworks Angular, React, or Vue, then state management library is a key factor they deal with. Several barriers persist while using Redux, which the Redux js toolkit attempts to address. As a result, the Redux team explicitly supports using this toolkit to eliminate issues. Now is the time for companies to prioritize this area of bespoke software development. How Redux works? Redux assists you in handling global state of your application. It effectively learns the app logic behavior in response to modifications made. The figure below depicts the Redux process of your application. Figure 1 Redux Workflow The main takeaway: A user interacts with the view to initiate an action event. Reducer receives the action from the dispatch event and updates the state accordingly. When the state is updated in the store the changes are modified via the subscription method and View updates its UI accordingly. To understand how redux works, it’s essential to learn three components of redux flow which are Action, Reducer, and store. I. Actions Actions are plain JavaScript objects with the required simple string property type and can include a custom property to update the state. Actions are not accountable for any state modifications, they merely describe what happens with the state. II. Reducer Reducer is a pure function. It takes the current value of the state and updates it according to dispatch action. III. Store A store is a state container that holds the app’s state. It manages all states and their updates effectively. Redux applications have only one store to manage the state.
Planning to Hire ReactJS developer? Your search ends here. See here Why Redux Toolkit over Redux? Redux patterns make states predictable, scalable, and easy to maintain due to the precise rule of how each unit in the redux flow should behave and work. However Redux comes with a few challenges: A developer has to write too much code to configure a store Too much code makes it hard to understand and less clean Too many packages need to be installed Writing reducers become more complex in Redux To overcome these challenges, the Redux team introduced Redux Toolkit which enables you write redux logic efficiently. Redux toolkit includes core redux packages with simple & clean redux code. How to use Redux Toolkit? Step 1: Install Packages

Install the required packages first in order to use Redux Toolkit and React-redux in your React application. npm install @reduxjs/toolkit react-redux Step 2: Create reducer and actions

In traditional redux, you may write actions and reducer functions separately just as shown below: Actions const INCREMENT = "INCREMENT"; const DECREMENT = "DECREMENT"; const RESET = "RESET"; export { INCREMENT, DECREMENT, RESET }; Reducer const intialState = { count: 0, }; const counterReducer = (state = intialState, action) => { switch (action.type) { case "INCREMENT": { return { count: state.count + 1, }; } case "DECREMENT": { return { count: state.count - 1, }; } case "RESET": { return { count: 0, }; } default: return state; } }; export default counterReducer; By using the Redux toolkit and createSlice, you may write better code with fewer lines.

Now, create a counterSlice.js file in the src/slice/ directory. The counterSlice file will look like this: counterSlice.js import { createSlice } from "@reduxjs/toolkit"; const counterSlice = createSlice({ name: "counter", initialState: { count: 0, }, reducers: { incrementCount(state) { state.count = state.count + 1; }, decrementCount(state) { state.count = state.count - 1; }, resetCount(state) { state.count = 0; }, }, }); export default counterSlice; export const counterSliceAction = counterSlice.actions; As you can see, the code is considerably better and understandable with less lines. It is not necessary to use switch case statements to manage actions with matching reducers. It also supported directly-assigning value to the state rather than returning the new value when updating the state. Step 3: Create and initialize the store Next, create a store.js file in the src directory of the project. The store holds the state of our application. To create a store, first you should import the configureStore from the redux-toolkit package.

Here the createStore in redux is replaced by configureStore. configureStore not only creates the store but also accepts reducer functions as an argument and automatically installs the Redux DevTools extension for debugging. import counterSlice from "./slices/counterSlice"; import { configureStore } from "@reduxjs/toolkit"; const store = configureStore({ reducer: { count: counterSlice.reducer, }, }); export default store; Here counterSlice reducer is imported from counterSlice.js and passed it to configureStore. Step 4: Provide the store to React application

Once done with creating the store, import the React-redux Provider and pass the store as a prop. This allows you to access the store from any component of your React application. import React from "react"; import ReactDOM from "react-dom/client"; import { Provider } from "react-redux"; import App from "./App"; import store from "./store"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( ); Step 5: Dispatch actions from the react component Now, create a Counter.js component in the src directory. And import the useSelector and useDispatch hook from the react-redux. Note: useSelector hook is used to read data from the store & useDispatch hook is used to dispatch or trigger an event.

Also, you need to import actions from counterSlice.js to trigger an event. import React from "react"; import { useDispatch, useSelector } from "react-redux"; import {userSliceAction} from "./slices/counterSlice" Now initialize the useDispatch and useSelector hook in a counter component. Here you may get the value of count using the useSelector hook and dispatch the event when the user clicks the increment, decrement, and reset button.

When a user hit one of these buttons, an event is fired in the counterSlice reducer based on the action's count update value. const Counter = () => { const count = useSelector((state) => state.count.count); const dispatch = useDispatch(); return ( <>Counter App Using Redux Toolkit {count} dispatch(counterSliceAction.incrementCount())}> Increment dispatch(counterSliceAction.decrementCount())}> Decrement dispatch(counterSliceAction.resetCount())}> Reset </> ); }; export default Counter; Here is the final output of your Redux toolkit-powered counter react application. Figure 2 Counter application using Redux Toolkit That’s it for this tutorial, stay tuned with iFour Technolab for more interesting and informative blogs. Read More: A complete guide on React fundamentals: Props and State Conclusion Redux enables developers to write simpler, more legible code while maintaining the redux in the appropriate flow and pattern. For beginners and developers, the Redux toolkit is a great option to reduce the amount of boilerplate code in Redux. In this blog, we discussed how Redux works, its limitations, and why you should use Redux Toolkit instead of Redux. We also learnt how to utilize the redux toolkit in a React project and develop redux code in a single file, including reducers and actions.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

How IoT-based Parking Management system helps the Fleet business?
How IoT-based Parking Management system helps the Fleet business?

Table of Content 1.How can IoT help the Fleet business? 2.Benefits of IoT-Based Parking in Fleet Management 3.Conclusion The Internet of Things (IoT) plays...

Read More
Healthcare Technology: A double-edged sword for Hospital Management
Healthcare Technology: A double-edged sword for Hospital Management

Table of Content 1.Data access is easier while information theft is a problem 2.Increased automation, decreased human connection 3.Improves efficiency while increasing...

Read More
What’s new in Node.js 18: A comprehensive guide
What’s new in Node.js 18: A comprehensive guide

Table of Content 1.Node 18 is now available! What changes does it bring? 2Browser-compatible APIs can be accessed globally 3Test Runner Module 4Web Streams API 5Build...

Read More