How to use Redux Toolkit with React

Last updated : December 5, 2022

Redux toolkit simplifies the usage of redux by providing a user-friendly interface. Here is how to use the Redux toolkit with a simple example.

Add Redux toolkit to an existing project.

yarn add @reduxjs/toolkit
or
npm install @reduxjs/toolkit

I still need react-redux to use the Redux toolkit with React. So, if you don't have it installed, here are the commands

yarn add react-redux
or
npm install react-redux

Alternatively, add the below entries to your package.json and run the yarn or npm update command.

"@reduxjs/toolkit": "^1.9.1",
"react-redux": "^8.0.5"

Create a state object.

The state object holds the application state. My application state consists of LoginState and CreditState, each with its initial state.

export interface LoginState {
    isLoggedIn: boolean
    isVarfied: boolean
}
export const initialLoginState: LoginState = {
    isLoggedIn: false,
    isVarfied: false
}

export interface CreditState {
    creditsLeft: number
    renewalDate: string
}
export const initialCreditState: CreditState = {
    creditsLeft: 100,
    renewalDate: "10-24-2024"
}

Creating slices in Redux Toolkit.

A slice in Redux Toolkit handles a portion of the state. My state has two sections, LoginState and CreditState. Therefore, I need two slices. The loginSlice handles the LoginState, and the creditSlice handles the CreditState. Each slice has its reducers defined under the reducers property.

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { CreditState, initialCreditState, initialLoginState, LoginState } from './state'

export const loginSlice = createSlice({
  name: 'login',
  initialState: initialLoginState,
  reducers: {
    setLoginState (state: LoginState, action: PayloadAction<LoginState>) {
        state.isLoggedIn = action.payload.isLoggedIn
        state.isVarfied = action.payload.isVarfied
        //return action.payload
    },
    setIsLoggedIn (state: LoginState, action: PayloadAction<boolean>) {
        state.isLoggedIn = action.payload
    },
    setIsVarfied (state: LoginState, action: PayloadAction<boolean>) {
        state.isVarfied = action.payload
    }
  }
})

export const creditSlice = createSlice({
    name: 'credit',
    initialState: initialCreditState,
    reducers: {

      setCreditsLeft (state: CreditState, action: PayloadAction<number>) {
            state.creditsLeft = action.payload
      },
      setCreditsRenewal (state: CreditState, action: PayloadAction<string>) {
            state.renewalDate = action.payload
      },
    }
  })
export const loginSliceActions = loginSlice.actions
export const creditSliceActions = creditSlice.actions

Creating the store in Redux Toolkit.

Like in plain vanilla Redux, I need a store that maps my reducers to the state. The configureStore accepts an object with a reducer property. That allows me to pass all the reducers I defined in my state slices.

import { configureStore } from '@reduxjs/toolkit'
import { creditSlice, loginSlice } from './reducers'

export const store = configureStore({
  reducer: {
    login: loginSlice.reducer,
    credit: creditSlice.reducer
  }
})

export default store
export type State = ReturnType<typeof store.getState>

Introducing the Redux provider.

Now it is time to introduce the state to my app components. I can do that in index.tsx or App.tsx.

import { Provider } from "react-redux";
import { Credit } from "./layout/credit_status";
import { Login } from "./layout/login_status";
import store from "./store/store";

const App = () => {
  return <Provider store={store}>
          <Login />
          <Credit />
        </Provider>
}
export default App;

Using the Redux state in components.

Now I am ready to use the state in my react components. The code below explains how to subscribe to the state and dispatch actions to change the state.

import { useDispatch, useSelector } from "react-redux"
import { loginSliceActions } from "../store/reducers";
import { State } from "../store/store";
export const Login = () => {
    const loginState = useSelector((state: State) => state.login)
    const dispatch = useDispatch();

    return (
        <>
            <p>Login status: {loginState.isLoggedIn ? "Logged-in" : "Logged-out"}</p>
            <p>Varification status: {loginState.isVarfied ? "Varified" : "Not Varified"}</p>
            <p><button onClick={() => dispatch(loginSliceActions.setIsLoggedIn(true))}>Set as Logged-in</button></p>
            <p><button onClick={() => dispatch(loginSliceActions.setIsVarfied(true))}>Set as varified</button></p>
            <p><button onClick={() => dispatch(loginSliceActions.setLoginState({isLoggedIn: false, isVarfied: false}))}>reset Login state</button></p>
        </>
    )
}
import { useDispatch, useSelector } from "react-redux";
import { creditSliceActions } from "../store/reducers";
import { State } from "../store/store";
export const Credit = () => {
    const creditState = useSelector((state: State) => state.credit)
    const dispatch = useDispatch();

    return (
        <>
            <p>Credits left: {creditState.creditsLeft}</p>
            <p>Varification status: {creditState.renewalDate}</p>
            <p><button onClick={() => dispatch(creditSliceActions.setCreditsLeft(creditState.creditsLeft + 100))}>Increase credit</button></p>
            <p><button onClick={() => dispatch(creditSliceActions.setCreditsRenewal("10-24-2023"))}>Change renewal date</button></p>
        </>
    )
}
L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments