top of page
Search
  • Writer's pictureJayant Kumar

Basics of Redux in React JS

Updated: Nov 20, 2023



Redux helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.


React helps you build component based application. Provides better routing functionality, helps to maintain state of component. Redux is a predictable state container for JavaScript apps. You can use Redux together with React, or with any other view library.

Redux helps centralizing your application's state and logic enables powerful capabilities like undo/redo, state persistence, and much more.


You can read the redux docs from here also.


Before move forward to the actual development, let's discuss about few redux terminologies

  1. Reducers

  2. Actions

  3. Dispatch

  4. Subscribe

Reducers

Reducers are those functions which takes two arguments a state and actions and returns a new state in result. State is an object which will have information/data of component. In other words, State of a component is an object that holds some information that may change over the lifetime of the component.

const MyReducer = (state={}, actions) {
    switch(actions.type) {
        case "ADD_USER":
            return {...state, users:actions.payload};
            break;
        default:
            return state; 
    }
}

Actions

Actions are object which contains type and payload. type define the action name

const myAction = {
type: "ADD_USER",
payload: [
{
    name: "John",
    email: "john.abc@mail.com"
}
];
export myAction;

Dispatch

Dispatch is a function of redux store. It tells react app to update state on the basis of actions object. Dispatch function takes object in argument and that object contains type and payload.

props.dispatch({
type: "",
payload: [{
    name: "JOHN",
    email: "email@email.com"
}]
})

Subscribe

Subscribe is a redux store. Adds a change listener. It will be called whenever a action is being dispatch and state has been updated. if you want to get the current state value, use getState().


Till now we have the basic understanding of redux terminologies. Now we can start the development.


create a react app.

npx create-react-app my-redux-app
npm install --save redux 

Remove other code from App.js file and paste below code.

import React from 'react';
import {createStore, combineReducers, applyMiddleware} from 'redux';

//initial state
//this will define the structure of your state
const initialState = {
    value:1,
    loadOldValues: []
}

//A reducer
const reducerAdd = (state = initialState, action) => {
    switch(action.type) {
        case "ADD":
            state = {
                ...state,
                value:state.value + action.payload,
            }
            break;
        case "SUBTRACT":
            state = {
                ...state,
                value:state.value - action.payload
            }
            break;
    }
    return state;
}

const logger = (store) => (next) => (action) => {
    console.log('this is logger');
    next(action);
}

const store = createStore(reducerAdd); //store state information

//if any state changed/updated it will subscribed
store.subscribe(() => {
    console.log('State updated', store.getState())
});

//dispacth and actions
store.dispatch({
    type:"ADD",
    payload:100
});
store.dispatch({
    type:"SUBTRACT",
    payload:10
});
store.dispatch({
    type:"ADD",
    payload:120
});

const App = () => {
    return (
        <>
            <p>To check result open browser console</p>
        </>
    )
}
export default App;

type npm start. Once your browser loaded a URL http://localhost:3000/, check you browser's console.


Suppose you have multiple reducers, combineReducers is the redux function which will combine more than one reducers.


Suppose you have one more reducers like reducerAdd function.

const reducerAdd2 = (state = initialState, action) => {
    switch(action.type) {
        case "ADD":
            state = {
                ...state,
                value:state.value + action.payload,
            }
            break;
        case "SUBTRACT":
            state = {
                ...state,
                value:state.value - action.payload
            }
            break;
    }
    return state;
}

update your createStore() function.

const store = createStore({reducerAdd, reducerAdd2});

And all set. Your redux project is ready, please try and enjoy.



17 views0 comments

Recent Posts

See All
bottom of page