Redux Toolkit: What it is and How to use it

Redux Toolkit: What it is and How to use it

If you are new to redux toolkit and don't know how and where to start it, this blog can be good for you.

ยท

5 min read

Hey, If you are new to redux toolkit then this blog can help you understand the basics of it.
we are not going to cover the redux toolkit in detail, but this will definitely help you in getting started

What is redux toolkit and why to use it

Redux is one of the most powerful libraries for managing states, Redux creates a global store which holds the state of the application and makes it accessible to all the components. But to get started with redux we needed to set it up, which was very hectic, But the redux toolkit simplifies this process for us.
The redux toolkit is an official toolset for writing redux logic Redux toolkit provides us some useful libraries and also make the code more readable and compact.

So is Redux core library is bad?

No, The Redux core library provides us flexibility in setting up store, state reducers, and much more things, But that flexibility is not always needed and as the official documentation states

Redux Toolkit 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"

Let's get started

Installation

If you are creating a new app using create-react-app.

#Redux + Plain JS template
npx create-react-app my-app --template redux

# Redux + TypeScript template
npx create-react-app my-app --template redux-typescript

or, add it to an existing project

# NPM
npm install @reduxjs/toolkit

# Yarn
yarn add @reduxjs/toolkit

After you've finished installing, it's time to create a store.

Creating a store

First thing first, what actually is a store,
A store is like a container which holds all of your application's state.
We can only have a single store in our app.

To create a store we need to create a file in your src/app folder named store.js,
Now our folder structure will look like this src/app/store.js.

After creating the file, Import the configureStore API from Redux Toolkit.

import { configureStore } from '@reduxjs/toolkit'

Now create a variable store with configureStore and pass an empty reducer to it.

import { configureStore } from '@reduxjs/toolkit'

export const store = configureStore({
  reducer: {},
})

We've created our store.

Now we need to provide our store to our app.

After we've created our store we need to provide it to our components,
We can do it by putting a React-Redux <Provider> around our application in src/index.js.

what is a provider?

A provider as the name suggests provides a value to its child components, just keep this in mind for now.
Now Import the store we just created and pass it as a prop to the provider.
Here we are passing the store to the provider, which makes the store accessible to all the childs.

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store } from './app/store'
import { Provider } from 'react-redux'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

We are done with setting our store. Half work done ๐ŸŽ‰

Now we need to create a slice.

what is a slice?

A slice is a slice/piece of the store, and In this piece of store, you can write your reducers.
Think of the store as a Cake, and a slice is just a piece of the cake.
Now that you've got this now let's create it.

Let's create a counter app, for this, we need to create a file named counterSlice in a new folder called features inside src.
src/features/counterSlice.js
In that file, import the createSlice API from Redux Toolkit and create a slice from it

import { createSlice } from '@reduxjs/toolkit'

export const counterSlice = createSlice()

Now we need to set a name, an initial state value, and one or more reducer functions to the create slice.
why Name? A name is required to identify the slice.

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  count: 0,
}

 export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
 increment: (state) => {
      state.count += 1
    },
}
)

Once a slice is created, we need to export the Redux action creators and the reducer function for the whole slice.

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: 0,
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.count += 1
    }
  },
})

// Actions are generated for each reducer function
export const { increment } = counterSlice.actions

// Exporting the slice reducer
export default counterSlice.reducer

Now we need to import our slice reducer into our store,

we need to define a field inside the reducers parameter, which tells the store to use this slice reducer function to handle all updates to that particular state.

import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counterSlice'

export default configureStore({
  reducer: {
    counter: counterReducer,
  },
})

And now we are almost finished with our small app,

Now we just need to import useReducer and useSelector from react-redux and also import our reducer function in our app.

import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { increment } from '../features/counterSlice'

export function Counter() {
  const count = useSelector((state) => state.counter.count)
  const dispatch = useDispatch()

  return (
    <div>
        <button
          onClick={() => dispatch(increment())}
        >
          Increment
        </button>
        <span>{count}</span>
    </div>
  )
}

Explaining useSelector

useSelector helps us select the store, and remember the store is nothing but an object.

so here useSelector returns us the whole store, and we are accessing the counter and then the count which is inside the counter. And dispatch is just dispatching the actions to the store.

And we are done with our app

Now every time you will click a button an action is dispatched, which will increase the count value in the slice, and as we know slice is a part of the store as we are accessing the store using useSelector our count value would also increment.

Thanks for reading ๐Ÿ˜„
Let me know if you have any doubts or queries about this,