React Redux

Avinashsoni
7 min readDec 18, 2021

--

#Basics :

Redux is a Predicatable State container for JS apps

  • Redux Application ke State ko store karne me kaam aata h

Redux ki madad se hum state me jo transitions ho rahe h unko track kar sakte h and unko manage kar sakte h

iske wajah se jo bhi changes hum application me karnege wo stable changes honge

baki agar state ko hume predictable way me manage karna h toh redux ka use karna hota h

# Why we need redux ?

lets see a distribution of Components in a APP :

now suppose hume A -> B state ko transfer karna h to hume sabse pehle A component se state ko lift karna parega to component C (parent component) and then waha se hum component B me us state ko as a props use kar paayenge.

this is what usually happens when state is managed without redux

so agar kafi complex application h (jisme kafi saare components h) to usme is tarah se (parent -> child) transitions karna parega to ye kafi difficult hoga

now to overcome this we use REDUX

now saare states hum redux store me store karnege to har component directly redux store se hi state ko as a props nikal sakte h to issue component lifting wala time bach jaayega

#React Redux :

3 important concepts of REDUX :

  1. Store : isme hum humare application ke states ko hold karte h
  2. Action: isme humko jo bhi changes karne h humare application me wo sab code karte h
  3. Reducers : ye action aur state ko as a parameter use karte h and jo bhi action hume perform karna h use ye perform karte h and state me us action se jo bhi changes honge wo karke state ko update karte h

so basically work of a reducer is :

. works on State and Action

. perform the action

. update the state

. return the updated state

Ex: Creating a Basic Counter App using Redux

Har task ko karne ke yeh steps h

  1. Component ko create karo
  2. actions ko define karo

2. action creators ko banao

3. initalstate ko define karo

4. reducer function ko likho

5. store me reducer ko pass karo

6. state ko map karo props ke saath

7 . actionCreators ko map karo props ke saath using dispatch()

8 . connect HOC see map wale functions ko export kar do along with component

9. now after this hume < Provider> ka use karna parega in order to connect store to the component

now the complete process of making this counter using redux

Step 1: Creating the react — app

create react app

Step 2 : Installing Dependencies

installing Packages

Step 3: creating the counter component

Counter.js

step 4: creating the action.js file

Action.js

step 5: creating the action creators

ActionCreator.js

step 6: creating the reducer

CounterReducer.js

step 7: creating the store :

step 8: completing the counter.js by mapping state and dispatch to props

Mapping to Props

step 9: using provider in App.js to connect store and the component

using Provider

counter application [ working] :

initial state
on clicking the add button
on clicking the remove button

Explaining a Few Things now :

  • <Provider > : React Redux includes a <Provider /> component, which makes the Redux store available to the rest of your app
  • createStore :

syntax : createStore(reducer, [preloadedState], [enhancer]

[ preloaded state ] : this is useful if suppose we are making a Product page and product will come from an API so in order to initially load something on page we can pass something here .

[enhancer] : in this hum middleware ko pass kar sakte h by using applyMiddleware() function

ex : logger ( which is used for logging in state transitions )

  • connect : function connects a React component to a Redux store.

#Modifiying the counter app by using payload :

Step 1 : add payload in the action creators

in the arrow function parameter give the initial state of the payload and then add payload to the object which we return

Adding Payload to the Object

step 2 : add action.payload in reducer function and also make sure that the changes are done in state directly we spread the state and then do the changes

also here in order to differentiate string concatenation from addition we need to use parseFloat to make the arithmetic addition

using payload in the reducer

step 3 : now in the component create a useState function taki hum ek input field se data ko store karke as a prop hum payload me bhej sake taki utne amount ke changes ho

complete procedure for this is :

  • import the useState Hook
imports
  • create a state
state
  • create a input field and usme onchange me hum value ko counter me store kara denge using setCounter and target karne ke lie e.target.value ka use kar lenge
taking input from text field
  • mile hue counter ko hum actioncreators me pass kar denge jaha humne payload ko number = 1 se initialize kia h as a base case
passing counter to actionCreators
  • also hum mapStatetoProps and mapDispatchtoProps me bhi cnt ko pass kar denge to map it with props
passing counter to dispatch methods

. finally we see that :

payload
initial counter
ADD button clicked
Remove button clicked

# Using Multiple Reducers :

app me more than one reducers agar create karnge to unko combine karke hi hum use store me use kar sakte h

iske lie hume combineReducer method ka use karna h :

Syntax for combineReducer() function

# React — Redux Hooks :

UseSelctor Hook :

yeh analogous h mapStatetoProps ke iske madad se hum redux store se data ko fetch kar sakte h

ex :

const counter = useSelector((state) => state.counter)

UseDispatch Hook :

This hook returns a reference to the dispatch function from the Redux store. You may use it to dispatch actions as needed.

const dispatch = useDispatch();

#Logger Middleware :

installation :

npm i redux-logger

usage :

with help of applyMiddleware() function we can use this

using logger

working :

counter app
logger functionality
details

#Redux Devtool Extension :

Installation of Web Browser :

extension

Package Installation :

installing redux-devtools-extension

how to apply ? :

import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';

const store = createStore(reducer, composeWithDevTools(
applyMiddleware(...middleware),
// other store enhancers if any
));
usage
usecase for counter in devtools

--

--

Avinashsoni

SDE@BNY MELLON | Spring Boot | Learning and Growing EveryDay 😁 Linkedln 👇: https://www.linkedin.com/in/asoni93/