DEV Community

Mnabawy
Mnabawy

Posted on

redux toolkit

in this post we will know how usefull redux toolkit is and what it prings to the table

-first lets configure redux store for the counter app the old way
-then lets fire some actions
-then i will write the same code with the toolkit

here is my redux setup with the old way


import { createStore } from "redux";

const initialState = {
  counter: 0,
};

// actions
export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";
export const RESET = "RESET";

// counter reducer
const counterReducer = (state = initialState, action) => {
  if (action.type === INCREMENT) {
    return {
      counter: state.counter + 1,
    };
  }
  if (action.type === DECREMENT) {
    return {
      counter: state.counter - 1,
    };
  }
  if (action.type === RESET) {
    return {
      counter: 0,
    };
  }

  return state;
};

// ccounter store
const store = createStore(counterReducer);
export default store;

//here we fire diffrent actions 
// increment
dispatch({type: INCREMENT})

// decrement
dispatch({type: DECREMENT})

// reset
dispatch({type: RESET})
Enter fullscreen mode Exit fullscreen mode

and here is the same approach with redux toolkit


import { configureStore, createSlice } from "@reduxjs/toolkit";
// initial state
const initialState = {
  counter: 0,
};

const counterSlice = createSlice({
  name: "counter",
  initialState: initialState,
  // here we replaced the reducer with this helper function which gives us ability to mutate the state directly 
  reducers: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    },
    reset(state) {
      state.counter = 0;
    },
    increase(state) {
      state.counter = state.counter + action.payload;
    },
  },
});

// actions to be used from inside the component later to make changes to our state 
export const counterActions = counterSlice.actions;

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

export default store;

//increment
counterActions.increment()

//decrement
counterActions.decrement()

//reset
counterActions.reset()

// and if you asking of course you can pass data (payload) 
like this 

for example as a parameter becase we still have access to the action payload
counterActions.increase(5)
Enter fullscreen mode Exit fullscreen mode

quik recap what we has accomplished so far
-we made a simple counter with react and redux with two ways
-the first way we used the old way of redux and it's a little confusing and complex to configure at first
-so here comes redux toolkit to solve this problm
-the mean reason for using toolkit is to simplify redux configuration
-here i am not talking about the pros and cons of using both methods a i prefered to just explain the diffrent in a practical way

hope you enjoy it
;)

Oldest comments (0)