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

Asesor, IA y Deep Tech

Wahbe, radicado en Ámsterdam, cuenta con una sólida experiencia en gestión de proyectos y cambios de TI, destacando su paso por el Ayuntamiento de Ámsterdam e ING. En 2019, se convirtió en Gerente de Programas en la división de Mercados Financieros de ING, especializándose en IA. Desde finales de 2022, Wahbe fundó Future Focus, ofreciendo servicios de consultoría e implementación de IA, y asistiendo a clientes en la maximización del potencial de la inteligencia artificial. Además, se desempeña como Asesor de IA y Deep Tech en Innovature, donde proporciona perspectivas estratégicas y orientación sobre tecnologías de IA de vanguardia.

Image of Wahbe Rezek

Jesper Bågeman

Socio, Tecnología

Jesper es un entusiasta de la tecnología comprometido a impulsar un cambio positivo a través de la tecnología. Lidera con tres principios fundamentales: fomentar alianzas genuinas con los clientes, integrar la sostenibilidad en las operaciones y priorizar el empoderamiento y el bienestar de los miembros del equipo. La dedicación de Jesper a estos valores garantiza que ofrezca resultados impactantes.

Image of Jesper Bågeman

Tiby Kuruvila

Jefe Asesor

Tiby es un experto en tecnología respetado, reconocido por sus contribuciones en gestión de proyectos y desarrollo tecnológico. Su dedicación al avance tecnológico y a la gestión de relaciones con los clientes lo ha establecido como un activo valioso para impulsar el crecimiento empresarial y mantener la satisfacción del cliente en diversos sectores.

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

Meghna George

Gerente de Recursos Humanos

Meghna se dedica a moldear las prácticas de Recursos Humanos y a fomentar una cultura de crecimiento y empoderamiento, guiando a Innovature hacia un futuro más brillante. Con una impresionante trayectoria en Recursos Humanos, Meghna ha liderado con éxito servicios compartidos de RR. HH. y ha gestionado la cartera de HRBP para grandes unidades de entrega. Su experiencia abarca la planificación estratégica, la gestión del cambio y el desarrollo de empleados, lo que la convierte en una fuerza fundamental para impulsar la excelencia organizacional.

Image of Meghna George, the HR manager

Unnikrishnan S

Vicepresidente

Unnikrishnan aporta una gran experiencia en la entrega de proyectos de software impactantes y en la implementación de iniciativas tecnológicas estratégicas. Su amplio conocimiento en gestión de proyectos, operaciones y compromiso con el cliente produce consistentemente resultados significativos, convirtiéndolo en un líder de confianza en el campo de las TI.

Image of Unnikrishnan S, Vice President of Innovature

Gijo Sivan

Director Ejecutivo, Global

Gijo tiene su sede en Japón y cuenta con veinte años de experiencia en tecnología web moderna, análisis de big data, computación en la nube y minería de datos. Juega un papel fundamental en la formación de la reputación global de la empresa, particularmente dentro de la industria de TI japonesa, y aporta una amplia experiencia en ventas, gestión de entregas, gestión de socios, operaciones y consultoría tecnológica.

Image of Gijo Sivan, Global CEO of Innovature

Ravindranath A V

Director ejecutivo, India y América

Ravindranath es un ejecutivo experimentado y de gran renombre por su dominio global en estrategia de TI, infraestructura y entrega de servicios de software. Con un enfoque en la innovación, transforma los conceptos de negocio de los clientes en soluciones prácticas en diversas industrias como la banca, el comercio minorista, la educación y las telecomunicaciones.

Image of Ravindranath, CEO of Innovature Americas