Redux State Management for React: A Comprehensive Guide

Microservice architecture is the new trend in the modern age of front-end development. The approach involves splitting various data flows/ separating the concerns of your application into the components. While this introduces many benefits and creates a degree of simplicity, it can also create complexity when several components depend on the same data.

React is a front-end library. Redux is managing the application’s state holds to a single global object called the store, and solves where the props need to be passed deep down into the component tree which is also called the ‘prop drilling’ problem. Redux’s fundamental principles help in maintaining consistency throughout the application, which makes debugging and testing easier.

Redux is a simple JavaScript library that helps to manage states in any JavaScript-based application such as React, Angular, Vue, etc.

Prerequisite:

  • Familiarity with React core concepts
  • Familiarity with async JavaScript

What is Redux?

The Redux pattern has several defining characteristics:

  • The state of your whole application is stored in an object tree within a single store (Single source of truth).
  • The store is immutable (it cannot be directly changed – instead changes create a new copy of the store).
  • Actions are dispatched on a shared message bus, handled by pure functions called reducers. Reducer is a pure function that takes state and action as arguments, returning a new state from the initial state.

REDUX data flow

The following figure shows the data flow of Redux state management:

View

Let us understand what is application state management and the different types of application states first. State management is the idea of sharing application data across multiple components within the same application where each component can read and modify the application state depending on the requirement. We have been emitting the event from here.

React component uses application state to render the portions of UI which have undergone changes without refreshing the complete page. The application state can be divided into two:

  • Local state – it’s the state which is used only inside a particular component and not being shared across any other components.
  • Global state – it’s the state which is being initialized in one parent component shared across multiple components which can be a direct child or part of a different component tree.

We can get the data from the store and the state gets the instantiation of the selector into the use Selector method from react-Redux library.

Import {use Selector} from ‘react-Redux’;
const username = useSelector(({auth}) => {
Return auth. Username
)

Action

Action is a simple JavaScript object that is used to send (dispatch) information from React components to other building blocks. It describes all the changes in the state of the application after the user interaction, internal events, and API calls.

Here’s the code of the Action object

{
type: “USER_LOGIN”,
Payload: {username: “John Doe”, password: “123456”}
}

Action must have ‘type’ property and optional payload data which should be communicated to other blocks. Action payloads can be read by reducers.

We can call the action object with the instantiation dispatch of the use Dispatch method from the react-Redux library

import {use Dispatch} from ‘react-Redux’Const dispatch = useDispatch()

//dispatching to the action creators functions
dispatch(authLogin(userCred))

Reducers

Reducers read the payloads from the actions and then update the store accordingly. It’s a pure function to return a new state from the initial state.

Function authReducer(state, action) {
switch (action.type) {
case ‘USER_LOGIN’:
return {…state,
auth: action. payload
}
default:
return state
}
}

Store

A store is an immutable object tree in Redux. A store is a state container that keeps the application’s state. Redux can have only one store in your application. Whenever a store is created in Redux, you need to specify the reducer. UI will be rendered automatically when the subscribe a selector call-back in a Redux store.

The store is created using the creator.
Store method from the Redux library

import {createStore } from “redux”;const store = createStore(authReducer)

You can pass it to the reducer function as a parameter. Now you are ready to dispatch an action that is managed by the reducer:

let userCred =

{ username: “johndoe”, password: ‘123456’ };

store.dispatch(authLogin(userCred));

The finalization of providing the store to be available for your application to our react components by putting a React Redux in the src/index.js file.
We can create the Provider selectors from the React-Redux library.

 

import { Provider } from ‘react-redux’import AppView from ‘./AppView’;

import { store } from ‘./store’

const App = () => {

return (

)

}

export default AppThis is how we start state management with React applications using React and React-Redux.

Conclusion

Redux is one of the most used libraries in state management for React applications. Redux has a lot of middleware libraries available in React such as Redux-Saga and Redux thunk, it’s especially used in handling API calls and side effects. We can write a standard way to Redux logic using ReactJS/toolkit. I hope this article will be a good first step in creating your own React application using Redux, React-Redux.

 

Wahbe Rezek

Adviseur, AI & Deep Tech

Wahbe, gevestigd in Amsterdam, heeft een solide achtergrond in project- en IT-verandermanagement, met name bij de Gemeente Amsterdam en ING. In 2019 stapte hij over naar Program Manager bij ING's Financial Markets divisie, gespecialiseerd in AI. Sinds eind 2022 heeft Wahbe Future Focus opgericht, waar hij AI-advies en implementatiediensten aanbiedt en klanten helpt het potentieel van kunstmatige intelligentie te maximaliseren. Daarnaast is hij Adviseur-AI & Deep Tech bij Innovature, waar hij strategische inzichten en begeleiding biedt op het gebied van geavanceerde AI-technologieën.

Image of Wahbe Rezek

Jesper Bågeman

Partner, Technologie

Jesper is een IT-enthousiasteling die zich inzet om positieve verandering te bewerkstelligen door middel van technologie. Hij leidt met drie kernprincipes: het bevorderen van oprechte partnerschappen met klanten, het integreren van duurzaamheid in de bedrijfsvoering, en het prioriteren van de empowerment en het welzijn van teamleden. Jespers toewijding aan deze waarden zorgt ervoor dat hij impactvolle resultaten levert.

Image of Jesper Bågeman

Tiby Kuruvila

Hoofdadvisuer

Tiby is een gerespecteerde technologie-expert, erkend voor zijn bijdragen aan projectmanagement en technologieontwikkeling. Zijn toewijding aan technologische vooruitgang en klantrelatiebeheer hebben hem gevestigd als een waardevol bezit in het stimuleren van bedrijfsgroei en het handhaven van klanttevredenheid in diverse sectoren.

Image of Tiby, on of Innovature's Co-founders

Meghna George

HR Manager

Meghna zet zich in om HR-praktijken vorm te geven en een cultuur van groei en empowerment te bevorderen, waarmee ze Innovature naar een betere toekomst stuurt. Met een indrukwekkende achtergrond in Human Resources heeft Meghna succesvol HR shared services geleid en de HRBP-portefeuille beheerd voor grote delivery units. Haar expertise omvat strategische planning, verandermanagement en werknemersontwikkeling, waardoor ze een cruciale kracht is in het nastreven van organisatorische excellentie.

Image of Meghna George, the HR manager

Unnikrishnan S

Vicepresident

Unnikrishnan brengt een schat aan ervaring met zich mee in het leveren van impactvolle softwareprojecten en het implementeren van strategische technologische initiatieven. Zijn uitgebreide kennis op het gebied van projectmanagement, operations en klantbetrokkenheid levert consequent opmerkelijke resultaten op, waardoor hij een vertrouwde leider is op IT-gebied.

Image of Unnikrishnan S, Vice President of Innovature

Gijo Sivan

CEO, Wereldwijd

Gijo is gevestigd in Japan en beschikt over twintig jaar ervaring in moderne webtechnologie, big data-analyse, cloud computing en datamining. Hij speelt een cruciale rol in het vormgeven van de wereldwijde reputatie van het bedrijf, met name binnen de Japanse IT-industrie, en brengt uitgebreide ervaring mee op het gebied van verkoop, delivery management, partner management, operations en technologieconsulting.

Image of Gijo Sivan, Global CEO of Innovature

Ravindranath A V

CEO, India & Amerika

Ravindranath is een doorgewinterde executive, bekend om zijn wereldwijde expertise op het gebied van IT-strategie, infrastructuur en levering van software services. Met een focus op innovatie vertaalt hij bedrijfsconcepten van klanten naar concrete oplossingen in diverse sectoren zoals de banksector, detailhandel, onderwijs en telecommunicatie.

Image of Ravindranath, CEO of Innovature Americas