DEV Community

Cover image for Redux Toolkit Simplified
Tanmay Agrawal
Tanmay Agrawal

Posted on

Redux Toolkit Simplified

Create a new React app with vite

npm create vite@latest my-app

Now installing the redux toolkit with this command

npm i @reduxjs/toolkit react-redux

so now the redux and redux-toolkit is installed , we now progress to create the store in the app

Install a plugin for the browser called Redux dev tools, this helps in development
https://chromewebstore.google.com/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?pli=1

  1. Create a store file in the src folder, we call it store.js store.js
import { configureStore } from "@reduxjs/toolkit";

//craete a store with configure store function of toolkit
const store = configureStore({
//create as many reducer you want
  reducer: {},

});
//export the store from the redux
export default store;
Enter fullscreen mode Exit fullscreen mode

2.Once the store is created, we now need to add provider to our app, this provider we usually provide in the app.js with Provider and we mention the store value there
app.js

import { Provider } from "react-redux";
import store from "./redux/store";

function App() {
  return (
    <Provider store={store}>
      <h1 className="font-bold text-5xl">Practicing Redux with toolkit</h1>
    </Provider>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

3.Now we need to create another file, let us say it as reducerSlice.js as by convention here we will define out initial state and then a name function which uses the createSlice method that takes an object with the values of name, initialState and reducer
- In the reducer, we will be defining actually the action functions which will take two arguments, first is the state and second will be the action.
- using the state we can apply the relevant action and by action we can hold the payload from the dispatch

  • This reducer function is then exported as default from here and will be then imported in the store to be mention with the reducer reducerSlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {

  //state variables

};

export const reducerSlice = createSlice({
    name : "Reducer Name",
    initialState,
    reducer : {
        typeOfAction : (state,action)=>{
            //action type defination
        }
    }
})

// these actions are used in the files where actions will be dispatched
export const {typeOfAction} = reducerSlice.actions;

//this default export will be imported in the store.
export default reducerSlice.reducer;

Enter fullscreen mode Exit fullscreen mode

store.js

import { configureStore } from "@reduxjs/toolkit";
import reducerSliceReducer from "./reducers" //note it comes from default exp.
//craete a store with configure store function of toolkit
const store = configureStore({
//create as many reducer you want
  reducer: reducerSliceReducer //imported from the reducers.js

});
//export the store from the redux
export default store;
Enter fullscreen mode Exit fullscreen mode

Now this was the part of Redux Toolkit, Now we need to use React hooks to combine this toolkit functionality

  • UseDispatch() and useSelector()
import {useDispatch, useSelector} from "react-redux"
import {typeOfAction} from "../redux/reducerSlice"

export default function App(){
    const dispatch = useDispatch() //calling the useDispatch
    const variable = useSelector(state => state.value) //useSelector grabs the state variable value to be used in the app
    const handleAction = ()=>{
        dispatch(typeOfAction()) //here dispatch is passed the action function declared in the reducerSlice we had exported earlier
    }
    return(

    )
}

Enter fullscreen mode Exit fullscreen mode

Simple example of using Redux toolkit

I have use theReact+vite+tailwind for this .

app.jsx

import { Provider } from "react-redux";
import store from "./redux/store";
import Number from "./components/Number";


function App() {
  return (
    <Provider store={store}>

        <h1 className="font-bold text-5xl container m-auto text-center">
          Practicing Redux with toolkit
        </h1>
        <Number />
    </Provider>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

store.js

import { configureStore } from "@reduxjs/toolkit";
import numWorkReducer from "./numWorkSlice";

const store = configureStore({
  reducer: numWorkReducer,
});

export default store;
Enter fullscreen mode Exit fullscreen mode

numWorkSlice.js

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

const initialState = {
  c: 0,
};



export const numWorkSlice = createSlice({
  name: "Counter",
  initialState,
  reducers: {
    increment: (state) => {
      state.c += 1;
    },

    incrementByValue: (state, action) => {
      state.c += action.payload;
    },

    decrement: (state) => {
      state.c -= 1;
    },

  },
});


export const { increment, incrementByValue, decrement } = numWorkSlice.actions;
export default numWorkSlice.reducer;
Enter fullscreen mode Exit fullscreen mode

Number.jsx

import { useDispatch, useSelector } from "react-redux";
import { decrement, increment, incrementByValue } from "../redux/numWorkSlice";
import { useState } from "react";



function Number() {

  const [value, setValue] = useState(null);
  const dispatch = useDispatch();
  
  const handleClick = () => {
    dispatch(increment());
  };

  const num = useSelector((state) => state.c);

  return (

    <div className=" p-5 w-fit text-center container m-auto bg-slate-100 shadow-md mt-5">
      <h1 className="font-bold text-3xl mt-10 ">Counter</h1>

      <p className="text-3xl">{num}</p>

      <div className="flex space-x-5">
        <button
          onClick={handleClick}
          className="outline-1 outline-sky-500 outline p-2 mt-5 bg-sky-300 rounded-md"
        >
          Increment
        </button>

        <button
          onClick={() => dispatch(decrement())}
          className="outline-1 outline-sky-500 outline p-2 mt-5 bg-sky-300 rounded-md"
        >
          decrement
        </button>

      </div>

      <div className=" flex space-x-5 items-center mt-5">

        <input
          className="outline outline-1"
          onChange={(e) => setValue(e.target.value)}
          value={value}
        />

        <button
          onClick={() => dispatch(incrementByValue(+value))}
          className="outline-1 outline-sky-500 outline p-2  bg-sky-300 rounded-md"
        >

          Add Value

        </button>

      </div>

    </div>

  );

}



export default Number;
Enter fullscreen mode Exit fullscreen mode

I Recommend, to Start a new app yourself, if you are new to this, And start with copy paste the code as I have mentioned here, Try to run it by yourself and play around with this to understand it better.

A good exercise will be to create another reducer, let us say, it does not counts but multiply the number with any given value input by the user, for this make a input form and a button to execute the dispatch function and render the output on the screen.

At this point you probably will get confuse in store.js

there is a simple solution in the store.js file, try to add the reducer object with the names of the reducer slice you import

const store = configureStore({
  reducer: {
    counter: numWorkReducer,
    multiply: multiplyWorkReducer,
  },
Enter fullscreen mode Exit fullscreen mode

Then in the hook useSelector(state=> state.counter.c) will fix the code for the counter and this is also needed for the other reducer that you create for the multiplication

Challenge!!

Try to create the fetch api using Axios, and use the url https://jsonplaceholder.typicode.com/
for sample url to fetch data for users, posts and comments
make three buttons to fetch the data on click and render on the screen.

Let me know! if you find this helpful, it helps me to make more posts in the future, let me know what can be improved and what can make such short refresher tutorials better in experience for readers!

Happy Coding!!! 😋

Top comments (0)