- ReactJS, Web Technologies

Redux Toolkit Better way to write Redux code in ReactJS

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 typescrip

// Yarn
yarn create react-app my-app –template typescripStep 2: Once the project is created move into the project folder using the below command:cd my-appStep 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-reduxProject 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.jsimport { 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.jsimport ReactDOM from ‘react-dom’;import { Provider } from ‘react-redux’;import App from ‘./App’;import { store } from ‘./store.js’;  ReactDOM.render(        ,  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.jsimport { createSlice } from ‘@reduxjs/toolkit’;  const initialState = {  name: [],  food: [],};  const customerSlice = createSlice({      name: ‘customer’,      initialState,      reducers: {    addCustomer: (state, { payload }) => {      state.name.push(payload);    },      orderFood: (state, { payload }) => {      state.food.push(payload);    },  },});  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.jsimport { 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.jsimport React, { useState } from ‘react’;import { useDispatch, useSelector } from ‘react-redux’;import { orderFood } from ‘./slice.js’;  function CustomerCard({ name }) {  const [orders, setOrders] = useState(”);      const food = useSelector((state) => state.customers.food);    const dispatch = useDispatch();      const addOrder = () => dispatch(orderFood(orders));    return (                  {name}                    {food.map((foo) => (            {foo}          ))}                                       setOrders(event.target.value)} />              Add                              );}  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 startThis is how the redux toolkit simplifies the usage of redux by avoiding all the boilerplate code.Reference: