Redux: Mastering State Management for Seamless Development

Tejas Patel
5 min readJun 26, 2023

--

This blog will help you to learn Redux in React which will ease your State management task in react while making large scalable applications.

What is State Management?

State management simply refers to sharing of data between diferent components. For example: You have an Expense Tracking Application. Here you have different components like Income, Expenses, Monthly Overview etc.. Data such as income, expense, total balance will be shared among components. They can be edited, deleted and modified from different components. It involves controlling how data is stored, updated, and accessed throughout the components of the application.

What is Redux?

Redux is an open-source JavaScript library used to manage application state. It is like a container where data is stored and retreived/updated when needed. It allows React components to read data from a Redux Store, and dispatch Actions to the Store to update data.

Redux has 3 components:

  • Reducer
  • Action
  • Store

Simple illustration to understand how it works:

Here, UI which are relatives (specially Goli) orders Jalebi Fafda which triggers action i.e Jethalal. Jethalal calls Abdul (reducer) and gives him instructions to bring jalebi fafda which is the payload. Abdul goes to Store and brings it.

Now getting more in detail here we have the architecture of the Redux:

Image Courtesy: JavaTpoint
  1. Store: Redux store is the main, central bucket which stores all the states of an application. It manages the status of the application and has a dispatch() function.
  2. Action: State in redux is read-only increasing security. Thus anyone who needs to modify the state needs to call action-creators or simply actions. Action includes type of action, time of occurrence, location of action etc. The simple format of action is as below:
{
type: "ORDER" // Note: Every action must have a type key
payload: {
bring: "Jalebi Fafda"
}
}

3. Reducer: Reducers are basically pure JS functions which take in the previous state and an action and return the newly updated state. They update/ reduce the state and return it just like Abdul did by brining food.

Implementation:

Here we have a very simple example of Credit/Deposit in balance kind of Bank management.

Components used: 1) Navbar 2) Balance/ Main Page

Both the components share the same data i.e balance

File Structuring
  1. Navbar.jsx

useSelector() is used to extract specific value from state.

import React from 'react'
import { useSelector } from 'react-redux'

const Navbar = () => {
const amount = useSelector(state => state.amount)
return (
<div>
<nav class="navbar" style={{backgroundColor: "#e3f2fd"}}>
<div class="container-fluid">
<form class="d-flex" role="search">
<button class="btn btn-outline-success disabled" type="submit">Balance: {amount}</button>
</form>
</div>
</nav>
</div>
)
}

export default Navbar

2. Balance.jsx (Main page):

Here we have imported useDispatch() function to dispatch an action

import React from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators } from './state';
import "./balance.css"


const Balance = () => {
const amount = useSelector(state => state.amount)
const dispatch = useDispatch();
const action = bindActionCreators(actionCreators, dispatch)

return (
<>
<div className="d-flex m-5">
<button class="btn btn-outline-success mx-2" type="submit" onClick={(() => {
dispatch(actionCreators.depositMoney(100))
})}>+</button>
<h3>Credit/ Debit</h3>
<button class="btn btn-outline-success mx-2" type="submit" onClick={(() => {
dispatch(actionCreators.withdrawMoney(100))
})}>-</button>
</div>
<div className="d-flex" id="balance">
<h2>Balance: {amount}</h2>
</div>
</>
)
}

export default Balance

3. action-creators/index.jsx

This file contains implementation of action. Here are two actions for depositing and crediting money into account.

export const depositMoney = (amount) =>{
return (dispatch) => {
dispatch({
type: "deposit",
payload: amount
})
}
}
export const withdrawMoney = (amount) =>{
return (dispatch) => {
dispatch({
type: "withdraw",
payload: amount
})
}
}

4. reducers/amountReducers.jsx

This is our reducer which takes two parameters. One is the state which is the initial value of state and second is action

const amountReducer = (state=0, action) =>{
if (action.type === "deposit") {
return state + action.payload
}
else if (action.type === "withdraw") {
return state - action.payload
}
else{
return state
}
}

export default amountReducer

5. reducers/index.jsx

Here we have combined different reducers. In our program there’s only one reducer but there will be more reducers in complex applications. amount is the key while amountReducer is the value. combineReducers() combine multiple reducers into root reducers.

import { combineReducers } from "redux";
import amountReducer from "./amountReducers";

const reducers = combineReducers ({
amount: amountReducer
})

export default reducers

6. state/index.jsx

In this file we have just imported all the action from the action-creators folder to the state folder.

export * as actionCreators from "./action-creators/index";

7. state/store.jsx

This is the brain of our redux application. Here we injected required methods from redux libraries and then created a store by passing reducers and a middleware which is thunk. {} represents initial state which is empty here. Thunk middleware allows you to write action creators that return functions instead of plain objects.

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import reducers from "./reducers"

export const store = createStore(reducers, {}, applyMiddleware(thunk))

8. src/index.js

After creating all the required files we need to add the <Provider> function in our index.js file of REACT. Pass store as props to <Provider>

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from 'react-redux'
import { store } from './state/store';


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store ={store}>
<App />
</Provider>
</React.StrictMode>
);
1) Shows the initial state of balance 2) Shows how balance is updated in both components (Navbar and Main page)

--

--