January 30, 2024
react.js - redux - redux-toolkit - state management
3 minutes

Redux Toolkit

A tool that becomes the setup of redux easily.

Redux Toolkit

Redux Toolkit is a tool that becomes the setup of redux easily.

Setup

  1. In any React project, install the following packages:
yarn add -D @reduxjs/toolkit react-redux
  1. Create a store file, and use the configureStore function to create a store.
// store.js
import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './rootReducer'

export default configureStore({
  reducer: rootReducer
})
  1. Create a root reducer file, and use the combineReducers function to combine all reducers.
// rootReducer.js

import { combineReducers } from '@reduxjs/toolkit'
import userReducer from './user/reducer'

const rootReducer = combineReducers({
  // here we can add any number of reducers as we need
  userReducer
})

export default rootReducer
  1. Create a slice reducer file, and use the createReducer function to create a reducer.

Slice is a collection of reducer logic and actions for a single feature of your app. It is the recommended way to organize your logic and data for a single feature in your app.

// user/slice.js

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
    currentUser: null
}

const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        login(state, action) {
            state.currentUser = action.payload
        },
        logout(state) {
            state.currentUser = null
        }
    }
})

export const { login, logout } = userSlice.actions

export default userSlice.reducer
  1. Provide the redux to whole application. We need to add it to the root component.
// app/page.jsx

import { Provider } from 'react-redux'

import store from './store'

const App = () => {
  return (
    <Provider store={store}>
      <div>
        {/* ... */}
      </div>
    </Provider>
  )
}

export default App

Usage

useSelector

useSelector is a hook that allows you to extract data from the Redux store state, using a selector function.

// components/navbar.jsx

import { useSelector } from 'react-redux'

const Navbar = () => {
  const { currentUser } = useSelector(rootReducer => rootReducer.userReducer)

  return (
    <>
      {currentUser && <div>{currentUser.name}</div>}
    </>
  )
}

export default Navbar

useDispatch

useDispatch is a hook that returns a reference to the dispatch function from the Redux store.

// components/login.jsx

import { useDispatch } from 'react-redux'

import { login } from './user/slice'

const Login = () => {
  const dispatch = useDispatch()

  const handleLogin = () => {
    dispatch(login({ name: 'John' }))
  }

  return (
    <>
      <button onClick={handleLogin}>Login</button>
    </>
  )
}

export default Login

References