Understanding Redux

Understanding Redux

Pramit Marattha
·Jun 7, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

REDUX

Why redux?

The data in react always flows from parent to child components which makes it unidirectional. So, redux plays a vital role to solve this kind of issue.

In react hooks (Context Api,useConext)

  • without context = App => user => user data

  • with context = (provider (App => user => consumer/useContext(user data)))

image

How redux solve the problem?

image

What is redux?

It is a library for managing and updating application state, using events called actions
It serves as a centralized store for the state that can be used across entire applications

ACTION ( What to do ?)

An action is a pure object
- Actions are plain javascript Objects that have a type field
- Actions only tell what to do, but they don't tell how to do it.

example,

 return {
     type:"INCREMENT",
     payload:num
 }

Action Creator

Pure function which creates an actions

export const incrementNumber =(num) =>{
 return {
     type:"INCREMENT",
     payload:num
 }
}

REDUCER (How to do ?)

Reducers are the functions that take the current state and an action as arguments and return a new state result.

const initialState = 0;

const incrementDecrementNumber = (state = initialState,action ) => {
    switch(action.type){
        case "INCREMENT":return state + action.payload;
        case "DECREMENT":return state - 1;
        default: return state;
    }
}

STORE (object which holds the entire state of the application)

Redux store combines state, actions, and reducers

  • There will only be a single store in a redux app.

  • Every redux store has a single root reducer function.

example,

import {createStore} from "redux";

const store = createStore(rootReducers);

Functions linked with the store.

createStore()
dispatch(actions)
getState()
 
Share this