Redux Toolkit Better way to write Redux code in ReactJS
Last Updated :
17 Jan, 2022
Redux Toolkit is used for writing redux code but in a more concise way. Redux Toolkit (RTK) solves three bigger problems that most of the developer's face who used redux in a react application.
- Too much code to configure the store.
- Writing too much boilerplate code to dispatch actions and store the data in the reducer.
- Extra packages like Redux-Thunk and Redux-Saga for doing asynchronous actions.
Creating a React Application and Installing Module:
- Step 1: Create a react application using the below command with typescript support:
// NPM
npx create-react-app my-app --template typescript
// Yarn
yarn create react-app my-app --template typescript
- Step 2: Once the project is created move into the project folder using the below command:
cd my-app
- Step 3: Now install Redux Toolkit via npm or yarn in our created project using the below command:
// NPM
npm install @reduxjs/toolkit react-redux
// Yarn
yarn add @reduxjs/toolkit react-redux
Project Structure: It will look like this.

Store Creation: Create a file called store.js by using the configureStore method from the redux toolkit package, pass in the list reducer's required for the application to initialize a store.
store.js
import { configureStore } from '@reduxjs/toolkit'
export const store = configureStore({
reducer: {},
})
Providing Store to React application: Once the store is created, we can provide the store to the react app using the Provider method from the react-redux package.
App.js
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import { store } from './store.js';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'),
);
Creating A Redux Slice: Create a slice.js file. In Redux Toolkit, we create a reducer using createSlice API from the redux toolkit package. It simplifies the creation of actions and the complex switch cases of a reducer into a few lines of code by internally using them.
slice.js
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
name: [],
food: [],
};
const customerSlice = createSlice({
// An unique name of a slice
name: 'customer',
// Initial state value of the reducer
initialState,
// Reducer methods
reducers: {
addCustomer: (state, { payload }) => {
state.name.push(payload);
},
orderFood: (state, { payload }) => {
state.food.push(payload);
},
},
});
// Action creators for each reducer method
export const { addCustomer, orderFood }
= customerSlice.actions;
export default customerSlice.reducer;
Even though the above code, we use to push it doesn't mutate the state value, since Redux toolkit uses immer library internally to update the state immutably.
Now, we import the reducer into the store.js file we created earlier. By defining a field inside the reducer parameter, we tell the store to use this slice reducer function to handle all updates to that state.
store.js
import { configureStore } from '@reduxjs/toolkit';
import reducer from './slice.js';
export default configureStore({
reducer: {
customers: reducer,
},
});
Using Redux state and actions in Components: We can use the react-redux hooks (useSelectore and useDispatch) to read the redux store values and dispatch actions to the reducers.
component.js
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { orderFood } from './slice.js';
function CustomerCard({ name }) {
const [orders, setOrders] = useState('');
// Using useSelector hook we obtain the redux store value
const food = useSelector((state) => state.customers.food);
const dispatch = useDispatch();
// Using the useDispatch hook to send payload back to redux
const addOrder = () => dispatch(orderFood(orders));
return (
<div>
<div className="customer-food-card-container">
<p>{name}</p>
<div className="customer-foods-container">
{food.map((foo) => (
<div className="customer-food">{foo}</div>
))}
<div className="customer-food-input-container">
<input value={orders} onChange={(event) =>
setOrders(event.target.value)} />
<button onClick={addOrder}>Add</button>
</div>
</div>
</div>
</div>
);
}
export default CustomerCard;
Step to Run Application: Run the application using the following command from the root directory of the project.
// NPM
npm start
// yarn
yarn start
This is how the redux toolkit simplifies the usage of redux by avoiding all the boilerplate code.
Reference:
Similar Reads
How Redux Toolkit simplifies Redux code in React application ?
Redux Toolkit is a powerful library designed to simplify the complexities of managing application state with Redux in React applications. At its core, Redux Toolkit provides developers with a set of utilities and abstractions that significantly reduce boilerplate code and streamline common Redux tas
5 min read
Why was Redux Toolkit created?
Redux Toolkit was created to improve the overall development experience and to simplify the setup of the redux store and state management tasks. Redux Toolkit is also known as RTK in short. In this article, we'll discuss the problems that developers face while using Redux and how Redux Toolkit comes
4 min read
How to Create Store in React Redux ?
React Redux is a JavaScript library that is used to create and maintain state in React Applications efficiently. Here React Redux solves the problem by creating a redux store that stores the state and provides methods to use the state inside any component directly or to manipulate the state in a def
4 min read
How to Use Redux Toolkit in React For Making API Calls?
In this article, we will explore how to use the Redux Toolkit in a React.js application to streamline state management and handle asynchronous operations, such as making API calls. Redux Toolkit's createAsyncThunk simplifies the creation of asynchronous action creators, allowing us to efficiently fe
4 min read
Benefits of using React-Redux over plain Redux
React-Redux streamlines state management in React applications by integrating seamlessly with Redux, eliminating prop drilling. It enhances predictability and scalability through centralized state management and facilitates the creation of reusable UI components. This integration optimizes syntax, a
5 min read
How to Migrate an Existing Redux Application to Redux Toolkit?
Migrating an existing Redux application to Redux Toolkit (RTK) can streamline your Redux code, reduce boilerplate, and improve maintainability. Here's a step-by-step guide to help you through the migration process. Prerequisites:ReduxReactJSJavaScriptSteps to Create Redux ApplicationStep 1: Create a
4 min read
What are the advantages of using Redux with ReactJS ?
Redux is a state management tool for JavaScript applications. It is more commonly used with ReactJS but is also compatible with many other frameworks such as Angular, Vue, Preact, as well as vanilla JavaScript. It is important to note that even though React and Redux are frequently used together, th
3 min read
Wishlist Functionality using Redux Toolkit in React
Wishlist is one of the important concepts of an E-commerce platform. In this article, we are going to learn how to implement Wishlist functionality using React JS and Redux Toolkit. Preview of final output: Let us have a look at how the final output will look like.Prerequisites React JS React ReduxR
6 min read
How does Redux Toolkit simplify Redux development?
Redux is a powerful state management library for JavaScript applications, but setting it up and managing boilerplate code can be cumbersome. Redux Toolkit is an official package from the Redux team designed to streamline Redux development and reduce boilerplate code. In this article, we'll explore h
5 min read
How to use React Context with React-Redux ?
React context with React-Redux is a popular state management library for React applications. Using React context with React-Redux is a powerful way to provide the Redux store to components deep within your component tree without manually passing it down through props. PrerequisitesNode.js and NPMRea
3 min read