Redux Toolkit in React
Easiest way to implement redux in your react project.

Redux Toolkit in React

Prerequisite:

Basic React, Redux, React hooks.

React and Redux is believed to be the best combination for managing state in large-scale React applications. However, with time, the popularity of Redux has fallen due to;

  • Configuring a Redux store is not simple.
  • We need several packages to get Redux to work with React.
  • Redux requires too much boilerplate code.

Redux Tool Kit Purpose

Redux Tool Kit provides some options to configure the global store and create both actions and reducers more streamlined by abstracting the Redux API as much as possible. It was originally created to help address three common concerns about Redux:

  • "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"

Main features of Redux Tool Kit API?

Redux Toolkit includes these APIs:

  1. configureStore(): A friendly abstraction over the standard Redux creates store function that adds good defaults to the store set up for a better development experience.
  2. CreateReducer(): Redux reducers are often implemented using a switch statement, with one case for every handled action type, but with this function, you don't have to use switch cases, you can pass an action name as directly as the method name and in that method name you will only update the state that is required, no need to pass a state with spread operator.
  3. createSlice(): accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.
  4. There are many other methods also but these three are necessary to know about, if you want to check out other methods you can click here.

Let's start with a simple example of the counter,

Redux Toolkit is available as a package on NPM for use with a module bundler or in a Node application:

Install it in your current react app.

# NPM

npm install @reduxjs/toolkitM
        

First, we will create a reducer file for it, name it counter.js


import { createSlice } from "@reduxjs/toolkit"

export const counterSlice = createSlice({

 name: "counter",

 initialState: {

  count: 0

 },

 reducers: {

  increment: (state) => {

   state.count += 1;

  },

  decrement: (state) => {

   state.count -= 1;

  },

  incrementByAmount: (state, action) => {

   state.count += action.payload;

  }

 }

});


//Action creators are generated for each case reducer function

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

export default counterSlice.reducer;
        

Now we have to create a global store, you can name it anything but for standardizing we will name it store.js.


import { configureStore } from "@reduxjs/toolkit"

import counterReducer from "./counter";

export default configureStore({

 reducer: {

  counter: counterReducer

 }

});
        

Now we will import this store in our main index.js file so the global store is available in all files.


import ReactDOM from "react-dom"

import { Provider } from "react-redux";

import App from "./App";

import store from "./redux/store";

const rootElement = document.getElementById("root");

ReactDOM.render(

 <StrictMode>

  <Provider store={store}>

   <App />

  </Provider>

 </StrictMode>,

 rootElement

);        

And now in our app component, we import this reducer and use redux to use this global store.


import React from "react"

import { useDispatch, useSelector } from "react-redux";

import { decrement, increment, incrementByAmount } from "./redux/counter";

export default function App() {

 const { count } = useSelector((state) => state.counter);

 const dispatch = useDispatch();

 return (

  <div className="App">

   <h1> The count is: {count}</h1>

   <button onClick={() => dispatch(increment())}>increment</button>

   <button onClick={() => dispatch(decrement())}>decrement</button>

   <button onClick={() => dispatch(incrementByAmount(33))}>

    Increment by 33

   </button>

  </div>

 );

};        

For code reference, you can follow this codesandbox example.

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics