How to Add Redux Toolkit to Your React Typescript App

How to Add Redux Toolkit to Your React Typescript App

This blog will help you to learn the redux toolkit with typescript. Basically, I used the redux toolkit for crud operation.

Redux Toolkit is a package that provides developers with a set of utilities for building Redux applications. It is designed to simplify and streamline the development experience by reducing boilerplate code and providing out-of-the-box support for common Redux use cases.

Table of Contents

Introduction to Redux Toolkit

The Redux toolkit provides some options to configure the global store and create both actions and reducers in a streamlined manner.

The Redux toolkit has the following APIs:

  • configureStore(): configureStore is used to create a Redux store that includes all the middleware and configuration options that are commonly used in a Redux application, such as redux-thunk, redux-dev tools-extension, and support for the serializable state. The function takes an object as an argument, which can be used to customize the behavior of the store.
  • createReducer(): createReducer can be defined as a slice reducer function used to update a specific portion of the Redux store's state. It takes an initial state object and a set of reducer functions as arguments and returns a new reducer function that can handle multiple action types and update the state accordingly.
  • createAction(): createAction is an action creator function that generates an action object when called. It takes a string that represents the action type as its argument and returns an action creator function that can be used to create actions of that type.
  • createAsyncThunk(): createAsyncThunk can be defined as an asynchronous action creator function that generates one or more actions in response to an asynchronous operation, such as a network request. It takes two arguments: a string that represents the type prefix for the generated actions and an asynchronous function that returns a Promise.
  • createEntityAdapter(): createEntityAdapter generates a set of reducer functions and selectors for a given entity type based on a schema that defines the shape of the normalized data. The generated reducers include functions for adding, updating, and removing entities and also handle the creation of unique IDs for each entity.
  • createSelector(): By using createSelector, you can define a selector that depends on one or more input selectors, and the result of the selector will only be recalculated if one of its input selectors changes.

Pre-requisite

  1. Proper knowledge of react terminology: JSX, TSX, Function and Class components, State, Props, and Hooks
  2. Familiarity with ES6 syntax and features.
  3. Understanding of redux terms and concepts
  4. Install the latest versions of the following:
    • React
    • React-Dom
    • React-Router-Dom
    • Typescript
    • For styling, I used the Chakra-Ui package. (you can also use material UI, bootstrap, or any other package for styling).

Difference between redux and redux-toolkit

  • Redux
    1. Configuring a redux store becomes too complicated.
    2. To use redux, we need to add a lot of additional packages.
    3. Redux requires too much boilerplate code.
    4. Cloning before updating the state.
  • Redux Toolkit
    1. No need to install any additional packages, just call getDefaultMiddleware which returns a list of all required packages.
    2. When we are using Redux Toolkit for state management, we don’t need to have separate files called reducer and action. Both can be kept together in one file.
    3. we can update the state directly without cloning

Technologies Used

  • React with typescript.

File structure for redux toolkit

file structure for redux toolkit

Installation of Redux Toolkit

  • If App is Existing: npm install @reduxjs/toolkit --save
  • Create New React App:
    1. npx create-react-app my-app –template redux (for javascript).
    2. npx create-react-app my-app –template redux-typescript(for typescript).

Setup Redux Toolkit

step-1: Create a Redux store.

import { configureStore } from '@reduxjs/toolkit';
import { bookSlice } from './bookSlice';

export const store = configureStore({
  reducer: {
    book: bookSlice.reducer,
  },
});

export type RootState = ReturnType<typeof store.getState>; 
export type AppDispatch = typeof store.dispatch;

Source file link: https://github.com/kuldippanchal2000/redux_toolkit_with_typescript/blob/master/src/redux/store.ts

step-2: Provide the Redux Store to react.

import { Provider } from "react-redux";
import { store } from "./redux/store";
<Provider store={store}>
 <App />
</Provider>

Source file link:
https://github.com/kuldippanchal2000/redux_toolkit_with_typescript/blob/master/src/index.tsx

step-3: Create a Redux state slice and actions.

import { createSlice } from "@reduxjs/toolkit";
import { RootState } from "./store";
import type { PayloadAction } from "@reduxjs/toolkit";
import { BookState } from "../types";

type initialStateType = {
  bookList: BookState[];
};
const bookList: BookState[] =
  JSON.parse(localStorage.getItem("userData") as string) ?? [];
const initialState: initialStateType = {
  bookList,
};
export const bookSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    addNewBook: (state, action: PayloadAction<BookState>) => {
      state.bookList?.push(action.payload);
    },
    updateBook: (state, action: PayloadAction<BookState>) => {
      const {
        payload: { title, id, author },
      } = action;

      state.bookList = state.bookList.map((book) =>
        book.id === id ? { ...book, author, title } : book
      );
      localStorage.setItem("userData", JSON.stringify(state.bookList));
    },
    deleteBook: (state, action: PayloadAction<{ id: string }>) => {
      const newArr = state.bookList.filter(
        (book) => book.id !== action.payload
      );
       localStorage.setItem("userData", JSON.stringify(newArr));
      state.bookList = newArr;
    },
  },
});
export const { addNewBook, updateBook, deleteBook } = bookSlice.actions;
export const selectBookList = (state: RootState) => state.book.bookList;
export default bookSlice.reducer;

Source file link: 
https://github.com/kuldippanchal2000/redux_toolkit_with_typescript/blob/master/src/redux/bookSlice.ts

step-4: Add slice reducers to the store.

import { configureStore } from '@reduxjs/toolkit';
import { bookSlice } from './bookSlice';
export const store = configureStore({
  reducer: {
    book: bookSlice.reducer,
  },
});
export type RootState = ReturnType<typeof store.getState>; 
export type AppDispatch = typeof store.dispatch; 

step-5: Use redux state and actions in react components.

import { addNewBook, updateBook,deleteBook } from "../redux/bookSlice";
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
const useAppDispatch = () => useDispatch<AppDispatch>();
const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

const dispatch = useAppDispatch();
dispatch(updateBook({ author, title, id: ids }));
dispatch(addNewBook(userData));
dispatch(addNewBook(userData));

Core Development Guide (CRUD Operation)

For designing use chakra-UI (npm install --save @chakra-ui/react) 
Use Router, Routes, and Route from (React-Router-Dom) for the routing in it.

Components

  • Loader.tsx (shows the loader when the site is rendered.)
  • Navbar.tsx (navigation bar in app.)

Pages

  • AddBook.tsx (main page for crud operations.)
  • DeleteBookModel.tsx(page for delete alert dialog.)

Redux

  • Store.ts (Redux store)
  • BookSlice.ts(Redux State Slice)

Create a Loader component for display loader for 2 seconds on rendering.

Source file link:
https://github.com/kuldippanchal2000/redux_toolkit_with_typescript/blob/master/src/components/Loader.tsx

create loader component

Create a Navbar using chakra-UI

import { Flex, Box, Text } from "@chakra-ui/react";
import { Link } from "react-router-dom";

const Navbar = () => {
  return (<Flex background="green.300" color="white"  fontSize="20"
      textDecoration="underline"
      display="flex"
      flexDirection="row"
      p={4}
    ><Box marginRight="10"><Link to="/"><Text>Home</Text>    </Link></Box></Flex>
  );
};

export default Navbar;

Source file link:
https://github.com/kuldippanchal2000/redux_toolkit_with_typescript/blob/master/src/components/NavBar.tsx

home

Create AddBook.tsx file for add, edit, and delete functionality.

Source file link: 
https://github.com/kuldippanchal2000/redux_toolkit_with_typescript/blob/master/src/pages/AddBook.tsx

add

1. Add Book Data

add book data

2. Edit Book Data

edit book data

3. Delete Book Data

Source file link:
https://github.com/kuldippanchal2000/redux_toolkit_with_typescript/blob/master/src/pages/DeleteBookModel.tsx

delete book data

On submitting the add, edit, and delete buttons, data is stored in local Storage.

book details

Get the data from local Storage and display it on the table of chakra UI

data from local storage

Final Output

final output

Conclusion

You're done with the code.

We hope your code is working as expected. To make your task even easier, we have created GitHub Repo at https://github.com/kuldippanchal2000/redux_toolkit_with_typescript. You can try the running demo app.

About Author

guest author Kuldip PanchalKuldip Panchal is a junior react and react native software developer. He started his career as a trainee at The One Technologies - the best ReactJs development company, in January 2022. So far, his journey has been good, challenging, and knowledgeable. He loves to find solutions for complex issues.

Playing kabaddi and cricket are his hobbies. He loves to spend time with his family & friends. His future goal is to become a technical project manager.

Certified By