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
Getting Started
Step 01: Installation
npm install @reduxjs/toolkit react-redux
Step 02: Create the store
Create a file
src/app/store.js
Create the empty store :
import { configureStore } from '@reduxjs/toolkit' export const store = configureStore({ reducer: {}, })
Provide the store to react app , In the index file :
Import a
Provider
from react-reduxwrap 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
Create a Features folder
Each state has his slice folder inside the Feature directory ( Let's take the doc example : Counter )
Import CreateSlice
import { createSlice } from '@reduxjs/toolkit'
Each Slice has Name , Initial State ,Reducers :
Initial state :
const initialState = { value: 0, }
Slice :
export const counterSlice = createSlice({ name: 'counter', initialState, reducers: { increment: (state) => { // Some changements // return the new state },
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
- 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
Read the data : with
useSelector
const count = useSelector((state) => state.counter.value)
Update the date (dispatch actions ) : with
useDispatch
import the useDispatch and the actions :
import { useSelector, useDispatch } from 'react-redux' import { decrement, increment } from './counterSlice'
define the dispatch :
const dispatch = useDispath()
use dispatch whener you want to use the actions
<button onClick={() => dispatch(increment())} > Increment </button>
THIS IS THE END , THANK YOU FOR READING .