ReactJS

How to Implement Redux in ReactJS?

Hello ReactJS Friends,

In this informative article, I will throw light on Redux in ReactJS.

The tutorial guide includes, What is Redux? How to Implement Redux in ReactJS? Example of Redux in ReactJS.

Let’s get started quickly 

What is Redux?

Redux is the state of your application that is kept in a store, and each component can access any state that it needs from this store at one centralized location.

Redux is a predictable state container for JavaScript applications. It helps you write apps that behave consistently, run in different environments (client, server, and native), and are easy to test. Redux manages an application’s state with a single global object called Store.

It’s worth mentioning that Redux is a standalone library and it’s pretty flexible. You can use it with React, Angular, jQuery, or even vanilla JavaScript. It works particularly well with React though, because React lets you describe the UI as a function of the state – and state management is what Redux does best. Components that need the data can access it directly from the store.

Working with Redux, you need the following 3 things:

  • Actions: These are objects that have two properties, one describing the type of action and the other describing what should be changed in the app state.
  • Reducers: These are functions that implement the behavior of the actions. They change the state of the app based on the action description and the state change description.
  • Store: It brings the actions and reducers together, holding and changing the state of the whole app. There is only one store.

Example of Redux in ReactJS:

Step 1: 

npm install redux react-redux --save
dependencies:
{
    "react-redux": "^8.0.5",
    "redux": "^4.2.0"
}

Step 2: app.js add store and provider

<Provider store={store}>
    <App />
</Provider>

Step 3: 

constans Action-type:
    export const ActionTypes = {
        SET_PRODUCTS: "SET_PRODUCTS",
    };

Step 4:

Reducer is a pure function that specifies how the application state changes in response to an action. Reducer handles action dispatch by the component. The reducer takes a previous state and action and returns a new state. Reducer does not manipulate the original state passed to them but makes their own copies and updates them.

import { ActionTypes } from "../constants/action-types";
export const setProducts = (products) => {
    return {
        type: ActionTypes.SET_PRODUCTS,
        payload: products,
    };
};

Step 5: Reducer define

import { ActionTypes } from "../constants/action-types";
const intialState = {
    products: [],
};
export const productsReducer = (state = intialState, { type,
    payload }) => {
        switch (type) {
            case ActionTypes.SET_PRODUCTS:
            return { ...state, products: payload };
            default:
            return state;
        }
    };

Combine Reducers file define

import { combineReducers } from "redux";
import { productsReducer, selectedProductsReducer } from
"./productsReducer";
const reducers = combineReducers({
    allProducts: productsReducer,
    product: selectedProductsReducer,
});
export default reducers;

Step 6:

A store is an object that brings all components to work together. It calculates state changes and then notifies the root reducer about it. The store keeps the state of your whole application. It makes the development of large applications easier and faster. The store is accessible to each component

import { createStore } from "redux";
import reducers from "./reducers/index";
const store = createStore(
    reducers,
    {},
    window.__REDUX_DEVTOOLS_EXTENSION__ &&
    window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;

Dispatch data

import { useDispatch, useSelector } from "react-redux";
const dispatch = useDispatch();
import { selectedProduct } from
../redux/actions/productsActions";
Const productDetails = {
    Id:1,
    name:”Computer”
    price:50000
}
dispatch(selectedProduct(productDetails ));

Get the product in store

import { useSelector } from "react-redux";
const products = useSelector((state) =>
state.allProducts.products);
console.log(products)

Conclusion:

I hope now you got a clear idea about What Redux is and How to Implement Redux in ReactJS. Explore more ReatJS Tutorials.

If you have any doubts, connect with me through the comment section. Stay with us to learn more about ReactJS.

Happy Coding!

Click to rate this post!
[Total: 5 Average: 4]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer ? with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket ?.

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

16 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

2 days ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

2 days ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

2 weeks ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

2 weeks ago