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.
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.
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.
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:
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.
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.
To begin, the Redux Toolkit makes it simple to create good Redux apps. Furthermore, it accelerates development by:
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.
We will be looking into two primary scenarios in this section:
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.
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;
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
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?
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.
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 multi-skilled IT consultant at CMARIX, a leading web app development company offers flexible hiring models to hire a dedicated developers. With…
FEW MORE POSTS BY Sunny Patel: