DEV Community

Cover image for A step-by-step guide on using Redux Toolkit with React
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

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.

Image description

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.

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

Enter fullscreen mode Exit fullscreen mode

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 };
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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(
        <react.strictmode>
        <provider store="{store}">
        <app>
    </app></provider>
  </react.strictmode>
);

Enter fullscreen mode Exit fullscreen mode

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"

Enter fullscreen mode Exit fullscreen mode

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 (
    <><div classname="container"><h3>Counter App Using Redux Toolkit</h3>
<h1>{count}</h1>
<div classname="btn-container"><button onclick="{()"> dispatch(counterSliceAction.incrementCount())}>
            Increment</button><button onclick="{()"> dispatch(counterSliceAction.decrementCount())}>
            Decrement</button><button onclick="{()"> dispatch(counterSliceAction.resetCount())}>
            Reset</button></div></div>

  );
};

export default Counter;

Enter fullscreen mode Exit fullscreen mode

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

Image description

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.

Top comments (0)