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

Conseiller, IA et Deep Tech

Basé à Amsterdam, Wahbe possède une solide expérience en gestion de projets et de changements informatiques, notamment à la Ville d'Amsterdam et chez ING. En 2019, il est devenu Program Manager au sein de la division Financial Markets d'ING, spécialisé dans l'IA. Depuis fin 2022, Wahbe a fondé Future Focus, une entreprise proposant des services de conseil et d'implémentation en IA, aidant les clients à maximiser le potentiel de l'intelligence artificielle. De plus, il occupe le poste de Conseiller IA et Deep Tech chez Innovature, où il apporte des perspectives stratégiques et des conseils sur les technologies d'IA de pointe.

Image of Wahbe Rezek

Jesper Bågeman

Partenaire, Technologie

Jesper est un passionné d'informatique engagé à apporter un changement positif grâce à la technologie. Il dirige selon trois principes fondamentaux : favoriser de véritables partenariats avec les clients, intégrer la durabilité dans les opérations et accorder la priorité à l'autonomisation et au bien-être des membres de l'équipe. Le dévouement de Jesper à ces valeurs garantit qu'il obtient des résultats percutants.

Image of Jesper Bågeman

Tiby Kuruvila

Conseiller Principal

Tiby est un expert technologique respecté, reconnu pour ses contributions dans la gestion de projet et le développement technologique. Son dévouement au progrès technologique et à la gestion des relations clients en a fait un atout précieux pour stimuler la croissance des entreprises et maintenir la satisfaction client dans divers secteurs.

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

Meghna George

Responsable des ressources humaines

Meghna se consacre à façonner les pratiques RH et à favoriser une culture de croissance et d'autonomisation, guidant ainsi Innovature vers un avenir plus radieux. Forte d'une expérience impressionnante en ressources humaines, Meghna a dirigé avec succès des services partagés RH et géré le portefeuille des HRBP pour de grandes unités de prestation. Son expertise couvre la planification stratégique, la gestion du changement et le développement des employés, faisant d'elle une force essentielle dans la promotion de l'excellence organisationnelle.

Image of Meghna George, the HR manager

Unnikrishnan S

Vice-président

Unnikrishnan possède une riche expérience dans la réalisation de projets logiciels percutants et la mise en œuvre d'initiatives technologiques stratégiques. Sa connaissance approfondie de la gestion de projet, des opérations et de l'engagement client produit systématiquement des résultats significatifs, faisant de lui un leader de confiance dans le domaine de l'informatique.

Image of Unnikrishnan S, Vice President of Innovature

Gijo Sivan

PDG, Monde

Basé au Japon, Gijo possède deux décennies d'expérience dans les technologies web modernes, l'analyse de données massives, le cloud computing et l'exploration de données. Il joue un rôle essentiel dans la construction de la réputation mondiale de l'entreprise, en particulier au sein de l'industrie informatique japonaise, et apporte une vaste expérience dans les domaines de la vente, de la gestion des livraisons, de la gestion des partenaires, des opérations et du conseil technologique.

Image of Gijo Sivan, Global CEO of Innovature

Ravindranath A V

PDG, Inde et Amériques

Ravindranath est un cadre expérimenté reconnu pour sa maîtrise mondiale de la stratégie informatique, de l'infrastructure et de la prestation de services logiciels. Axé sur l'innovation, il traduit les concepts commerciaux des clients en solutions réalisables dans des secteurs diversifiés tels que la banque, le commerce de détail, l'éducation et les télécommunications.

Image of Ravindranath, CEO of Innovature Americas