A Complete Guide To Redux Toolkit with Typescript

A Complete Guide To Redux Toolkit with Typescript
Table of Contents

A state manager is something you’ve probably used if you’ve worked with React for any length of time.

To many of us, Redux was the actual state manager since it was good at what it promised: managing the state. It is critical to emphasize that both of these methods require a learning curve in order to be used effectively. This viewpoint is based on the fact that whenever the term “Redux” is introduced, its high intricacy and verbosity come to mind. This is especially noticeable when using the redux toolkit with typescript.

The problem was that Redux required a lot of code to start and had a lengthy learning curve for the smallest app. The developer community voiced their dissatisfaction loudly, and the Redux team noticed. We will discuss Redux Toolkit, an original Redux package that makes it simple to configure and access all of Redux’s resources in this article.

What is Redux?

Redux is a JavaScript open-source library for preserving and centralizing application state. It is most typically used for designing user interfaces using libraries like React or Angular. It is similar to the Flux architecture of Facebook and even inspired by it.

What is Typescript?

Microsoft TypeScript is an open-source programming language. It is a tight syntax JavaScript superset and extends the language with optional static typing. Types allow you to specify the geometry of an object, which improves documentation and allows TypeScript to test whether your code is functioning properly. Existing JavaScript programmers are also valid TypeScript programmers because TypeScript is a part of JavaScript.

What is Redux Toolkit?

The original Redux tool, intuitive, with cells for efficient Redux development, is Redux Toolkit. It offers various valuation models that ease the most frequent Redux use cases, such as:

  • Configuration should be saved.
  • Dimming the lights.
  • Update logic that is immutable

You can also use it to build complete “slices” of state simultaneously without having to manually write any action creators or types of actions.

It also includes the most popular Redux insert, such as Redux Thunk for sequential logic and Reselect for building selector functions, so you can start using them right away. The Redux Toolkit is essentially aimed to be the conventional way of building Redux logic, and it is strongly advised that you utilize it.

Redux Toolkit offers tools that let us abstract over the previously difficult setup process. In order to cover the most common use cases, it also includes certain handy functions which were successful with the standalone Redux. It is one of the best JavaScript frameworks in the market today.

Redux toolkit in Next.js and Typescript

Next.js and Typescript

When a project requires React, developers typically use Next.js as their technology for development. It includes many of the features we look for when delivering production-ready programmers. They also utilize TypeScript as it helps them produce less error-prone code, serves as documentation, and aids in long-term project maintenance. Thus react redux toolkit typescript can be used here.

Why Should you use Redux Toolkit?

To begin, the Redux Toolkit makes it simple to create good Redux apps. Furthermore, it accelerates development by:

  • Adherence to best practices
  • Providing appropriate default behavior.
  • Error detection.
  • Making it simpler to write code.

Overall, regardless of its ability level or experience, the Redux Toolkit is valuable to all Redux users. This applies whether you are a beginner Redux user starting your first project or an expert Redux user looking to simplify an existing app. Thus companies hire web developers to create groundbreaking apps using this tool.

How to Start with the Redux Toolkit Typescript?

We will be looking into two primary scenarios in this section:

  • Integration with an existing project.
  • Making a new project

1. Implementation within an existing project

Step 1.

Add the following dependencies to your project:

npm install @reduxjs/toolkit react-redux

yarn add @reduxjs/toolkit react-redux

Step 2.

Make a file for your Redux Store once the dependencies have been installed. For instance, src/store/index.ts

You must use the Redux Toolkit’s “configureStore” function within this file to build your store and then export it.

Note: configureStore is a function that gives streamlined configuration choices for combining all of your reducers or adding any middleware.

import { configureStore } from ‘@reduxjs/toolkit

Step 3.

React requires the Redux Store:

import React from ‘react’;

import ReactDOM from ‘react-dom’;

import App from ‘./App’;

import { store } from ‘./store’;

import { Provider } from ‘react-redux’;

ReactDOM.render(

<React.StrictMode>

<Provider store={store}>

<App />

</Provider>

</React.StrictMode>,

document.getElementById(‘root’)

);

Step 4.

Use the Redux Toolkit’s createSlice function to generate your reducers.

In this function, you must specify three parameters: name, initialState, and reducers.

  • name: Used in action types (String)
  • initialState: Initial state for the respective reducer (any)
  • reducers: An object of reducer functions. Key names will be used to generate actions.(Object<string, function>)

We can use Redux Toolkit to implement “mutating” logic in reducers. It does not, however, mutate the state since it employs the Immer library, which detects changes to a “draught state” and generates a completely new unchangeable state based on such changes:

import { createSlice, PayloadAction } from ‘@reduxjs/toolkit’

export interface CounterState {

value: number

incrementAmount: number

}

const initialState: CounterState = {

value: 0,

incrementAmount : 1

}

export const counterSlice = createSlice({

name: ‘counter’,

initialState,

reducers: {

increment: (state) => {

state.value += state.incrementAmount

},

decrement: (state) => {

state.value -= state.incrementAmount

},

changeIncrementAmount: (state, action: PayloadAction<number>) => {

state.incrementAmount = action.payload

},

},

})

export const { increment, decrement, changeIncrementAmount } = counterSlice.actions

export default counterSlice.reducer

Step 5.

Add the reducer to the store after you’ve finished it:

import { configureStore } from ‘@reduxjs/toolkit’

import counterReducer from ‘./counterReducer’

export const store = configureStore({

reducer: {

counter: counterReducer,

},

})

export type RootState = ReturnType<typeof store.getState>

export type AppDispatch = typeof store.dispatch

Step 6.

Then, within your components, you may leverage the redux state and Actions.

Use the “useSelector” function to read data, and the “useDispatch” function to dispatch actions:

import { useSelector, useDispatch } from “react-redux”;

import { RootState } from “./store”;

import { increment, decrement, changeIncrementAmount, } from “./store/counterReducer”;

function App() {

const count = useSelector((state: RootState) => state.counter.value);

const dispatch = useDispatch();

const incrementAmount = useSelector(

(state: RootState) => state.counter.incrementAmount

);

function handleChange(incrementAmountValue: string) {

dispatch(changeIncrementAmount(Number(incrementAmountValue)));

}

return (

Counter

dispatch(decrement())}>

{count}

dispatch(increment())}>

+

Change Increment Amount

handleChange(e.target.value)}

/>

);

}

export default App;

Looking for a Dedicated Developers

2. Making a New Project

It is quite simple to start a new project with Redux Toolkit. You just need to enter the following command:

npx create-react-app APPLICATION_NAME –template redux-typescript

The CRA will be utilized behind the scenes to develop your React application. In the end, you’ll have something like this:

– src

– app

– hooks.ts

– store.ts

– Features

– counter

– counter.module.css

– counter.tsx

– counterAPI.ts

– counterSlice.spec.ts

– counterSlice.ts

  1. app/hooks.ts: While RootState and AppDispatch types can be imported for each component, it is preferable to construct typed versions of the “useDispatch” and “useSelector” hooks for use in your app. This allows you to load them into any part files that require the hooks, avoiding the possibility of circular import dependence concerns.
  2. app/store.ts: There is no additional typing required to utilize the “configureStore” method. However, inside files that require this reference, you should use RootState and Dispatch types. As a result, these definitions are generated and exported in the store.ts file.
  3. features/counter/counter.module.css: Simply the file containing the stylizations of the produced component.
  4. features/counter/counter.tsx: The main component file contains dispatch function triggers and dynamic memory data. In addition to the presence of all HTML structures.
  5. counterAPI.ts: A dummy function is included to simulate an asynchronous message request.
  6. counterSlice.spec.ts: The file where the major aspects of the component’s tests are created.
  7. counterSlice.ts: The place where reducers and actions are defined, as well as all of the algorithms to maintain the global state and control in order to ensure data consistency at all times.

The creation of both big and small apps can be a good Redux toolkit typescript example.

You May Also Like : Why Use ReactJS For Developing Websites And Mobile Apps?

How to install the Redux toolkit in Typescript and Next.js?

  1. Make a replica of the Next + TS initialization project.
  2. Once the packages have been cloned, install them and remove the components, interfaces, pages, and utils directories, which include items that will not be used in this example.
  3. Create an src directory in the project’s root and three subdirectories: pages, features, and app.
  4. Make an index.tsx file in the pages directory. Develop a functional component and some content, such as “hello world,” so that you have something to look at when you proceed to the next stage.
  5. For getting the project running on dev, use yarn dev or npm run dev (based on your package management).

After completing the preceding steps, you must be enabled to see http://localhost:3000/ open with your “hello world” text from the index.tsx file.

CONCLUSION

As a very flexible development tool, Redux Toolkit is used by programmers for a wide variety of purposes. If you are a solo programmer working on a small project, it’s logical to use Redux Toolkit in a way that many devs working on a huge project would not. Redux Toolkit is an amazing tool for increasing the productivity of Redux-based applications, and when combined with Typescript, your applications will be dependable and simple to maintain.

While Redux may be used to build anything, the intricacy and verbosity make development slower and demand a steeper learning curve. If you are not a programmer and still looking forward to making a great app using this versatile toolkit, hire dedicated developers for the same.

Written by Sunny Patel

Sunny Patel is a versatile IT consultant at CMARIX, a premier web app development company that provides flexible hiring models for dedicated developers. With 11+ years of experience in technology outsourcing, he spends his time understanding different business challenges and providing technology solutions to increase efficiency and effectiveness.

Ready to Build Your Own Web App?
Follow ON Google News
Read by 1035
Quick Look

Related Blogs

React With Python: Full Stack Development for Robust Web Applications

React With Python: Full Stack Development for Robust Web Applications

A state manager is something you’ve probably used if you’ve worked with […]

How To Develop Framer Plugin?

How To Develop Framer Plugin?

A state manager is something you’ve probably used if you’ve worked with […]

How to Create an eLearning Platform Like Coursera?

How to Create an eLearning Platform Like Coursera?

A state manager is something you’ve probably used if you’ve worked with […]

Hello.
Have an Interesting Project?
Let's talk about that!