Getting started with Redux toolkit

Getting started with Redux toolkit

Introduction

What is Redux toolkit?

You have heard of redux right! It is a state management library. Well yes, this is a kind of newer and improved version of the redux core. It is built to overcome some of the flaws in redux core so that you encounter less number of bugs when building an application.

Prerequisite

You must have a basic understanding of redux. As what a store, reducer, action, etc. is. So, if you do not have that knowledge you might want to go check them out first.

Installation

There are a few packages that need to be installed along with the redux toolkit to be able to start using it.

npm install react-redux
npm install @reduxjs/toolkit

Configure store

To configure a store we are provided with the method configureStore which in the core was as createStore. Configuring a store is much simpler as compared to the earlier method.

We have to import configureStore from reduxtoolkit

import { configureStore } from '@reduxjs/toolkit';

So, configureStore takes in an object as a parameter, where we can pass reducer, middleware, etc. Suppose we have a cart state to manage so we have to pass a reducer named cartReducer as shown below.

This is a basic setup of a store.

const store = configureStore({
    reducer: {
        cart: cartReducer, // This is an example
    },
});
//You can pass multiple reducers

//At last you need to export the store
export default store;

Provider

Now let's quickly set up the provider, This is how your app will get access to the store.
It's quite simple, just a few lines to add to your App.js.

You have to import Provider from react-redux.

import { Provider } from 'react-redux';

Then just wrap the provider to the root App and pass the store as a prop. And this is it. Don't forget to import the store.

import store from './store';
<Provider store={store}>
   <App/>
</Provider>

Slice

So we have something called createSlice, what is it?

It is used to create the reducer and actions which we have imported into the store. It also accepts an object as a parameter and in that object, we can pass name, initialState and reducers.

Import createSlice from the redux toolkit

const { createSlice } = require('@reduxjs/toolkit');

This is an example of using a createSlice.

const cartSlice = createSlice({
    name: 'cart',
    initialState: [],
    reducers: {
        add(state, action) {
            state.push(action.payload);
        },
        remove(state, action) {
            return state.filter((item) => item.id !== action.payload);
        },
    },
});

One advantage of the createSlice function is that even if you mutate a state directly even then the state will be updated and the component will re-render.

const cartSlice = createSlice({
    name: 'cart',
    initialState: [],
    reducers: {
        add(state, action) { //This is the action you want to perform
            state.push(action.payload); //This is allowed in redux toolkit
        },
        remove(state, action) {
            return state.filter((item) => item.id !== action.payload);
        },
    },
});

We have almost completed setting up the basic usage of the redux toolkit

Now let's try and see how we have to use the store.

We have two hooks to be able to perform actions or get data from the store. We have to import them both from react-redux.

import { useSelector, useDispatch } from 'react-redux';
  • useDispatch : This is used to perform or dispatch actions
    Example usage :
import { useSelector, useDispatch } from 'react-redux';
import { remove } from '../store/cartSlice'; //Import the actions from cartSlice

const dispatch = useDispatch();
const handleRemove = (productId) => {
        dispatch(remove(productId));
    };
  • useSelector : It is used to get the data from the state and select one.
    Example usage :
    const products = useSelector((state) => state.cart); // You'll get all the data that is in cart
    

This is it, we have successfully set up the basic usage of the redux toolkit.

But this is not all, there are more features and advantages that can be implemented for better functioning of an App. To find out more you can check out the official documentation. Till then keep exploring.