Steps to use redux-toolkit with React app

Steps to use redux-toolkit with React app

This tutorial has no definitions or explications , it's just a todo steps to add redux-toolkit to your React application

·

2 min read

Getting Started

Step 01: Installation

npm install @reduxjs/toolkit react-redux

Step 02: Create the store

  1. Create a file src/app/store.js

  2. Create the empty store :

     import { configureStore } from '@reduxjs/toolkit'
    
     export const store = configureStore({
       reducer: {},
     })
    
  3. Provide the store to react app , In the index file :

    1. Import a Provider from react-redux

    2. wrap the <app/> with the Provider

       import App from './App'
       import { store } from './app/store'
       import { Provider } from 'react-redux'
      
       ReactDOM.render(
         <Provider store={store}>
           <App />
         </Provider>  
       )
      

Step 03: Create the state slice

  1. Create a Features folder

    Each state has his slice folder inside the Feature directory ( Let's take the doc example : Counter )

  2. Import CreateSlice

     import { createSlice } from '@reduxjs/toolkit'
    
  3. Each Slice has Name , Initial State ,Reducers :

    1. Initial state :

       const initialState = {
         value: 0,
       }
      
    2. Slice :

       export const counterSlice = createSlice({
         name: 'counter',
         initialState,
         reducers: {
           increment: (state) => {
       // Some changements
       // return the new state
           },
      
    3. Export the reducers function and the full reducer of the slice

       // reducers function
       export const { increment} = counterSlice.actions
       // full reducer
       export default counterSlice.reducer
      

Step 04: Add Slice Reducers to the Store

  1. Import the reducer as StateReducer

Add the Reducer to the reducers store as : state : ReducerOfThisState

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

export const store = configureStore({
  reducer: {
    //The state counter is updated by counterReducer
    counter: counterReducer,
  },
})

Step 05: Use the State and the actions

  1. Read the data : with useSelector

     const count = useSelector((state) => state.counter.value)
    
  2. Update the date (dispatch actions ) : with useDispatch

    1. import the useDispatch and the actions :

       import { useSelector, useDispatch } from 'react-redux'
       import { decrement, increment } from './counterSlice'
      
    2. define the dispatch :

          const dispatch = useDispath()
      
    3. use dispatch whener you want to use the actions

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

THIS IS THE END , THANK YOU FOR READING .