React-Redux

React-Redux

Introduction to Redux

Why REDUX?

-Normally in React how to pass data?

The data in React always flow from parent to child component which makes it unidirectional. ( It is not possible, we can send data from child to parent ).

{ How to overcome the issue to pass data in react, So the answer is with props drilling }

How does Redux solve the problem?

What is Redux?

Redux is a pattern and library for managing and updating application state, using events called action. it serves as a centralized store for a state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable function.

Redux main topics

  • Action (What to do?)

  • Reducer (How to do?)

  • Store (Objects which hold the state of the application)

  • The function associated with store (eq. CreateStore(), dispatch(action), getState() )

Redux Basic

Action- Pure object
-Actions are plain JavaScript object that has a type field. The action only tells What to do, but they don't tell how to do.

As: Increments/Decrement counter using react and redux

-Minus Button48+ plus Button
//There are two buttons "Clicking on plus button or minus button as an action".it returns

// Two action Performed (increment/decrement)
return {
    type: "increment",
    payload: num
}
//OR
return {
    type: "decrement",
    payload: num
}

So, we have to inform the application that we have one action which is increment/decrement.

Who is creating an Action?

-Action Creator (Pure function which creates an action).

export const increaseNumber = () =>{
    return {
         type: "increment",
         payload: num
    }
}

Now it is the complete action, which is reusable, portable and easy to test.

Reducer

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

const initialState = 0;
const changeTheNumber = (state = initialState, action )=>{
    switch(action.type){
        case "increment": return state+action.payload;
        case "decrement": return state-1;
        default: return state;
    }
}

Store

The Redux store brings together the state, action and reducers that make up your app.

It's important to note that you'll only have a single store in a Redux application.
Every Redux store has a single root reducer function.

import {createStore} from 'redux';
const store = createStore(rootReducer);

Git link for your reference: https://github.com/Rahul8883/react-redux-example

Redux Principle

  • Single source of truth - The global state of your application is stored as an object inside a single store.

  • The state is Read-only - The only way to change the store is to dispatch an action.

  • Immutability, one-way data flow, predictability of the outcome.

  • Changes are made with the Pure Reducer function.