Redux - Basic Understanding via React
Redux basics by Vinod Chauhan

Redux - Basic Understanding via React

Hello Connections, Today we will discuss about 'Redux'. In this excursion, we will cover basic understanding of Redux, why we need Redux ?,how it works ?, how we can connect it with react ?, What are its benefits compared to normal state & props. So let's get started without wasting any more time.

First of all, To become well-versed in Redux we need to know why we need this. To make our concepts clear lets say we own a Bank 'XYZ' for instance. In 'XYZ' bank, the paramount features are 'withdrawl' & 'deposit' money in a bank. For these features we can have different options from where our customer can do both the things.

XYZ bank features $ options

Considering all options regarding features as a developer we need to make a real source of truth to which we can trust and replicate to our every options so that there will no mismatch in the amount of money at the time of their transactions. To complete our job with efficacy we need to make central actions where our all options can come and use them to complete bank amenities. So we can make two actions 'Withdraw' & 'Deposit' as a common action which connect to our 'Central Server' to update DB of the customer. In this way, whenever a customer access his account from any of the options given to him, he found the amount of money is same before or after (his/her) transaction.

As we discussed above, there must be a Central 'store' & 'action' where all our CRUD operations can come and get their data from a single source of truth. So lets' get started with redux official docs statement :

Redux is a state management library that gives you access to the state anywhere in your components without the need to pass props. So it can be used with any front-end libraries like Angular and React but it works best with React. ‘react-redux’ is the official library that connects the two.

No alt text provided for this image

In the pic above, we can see a REDUX FLOW between 2 components or pages. Suppose we have an app where we maintained a redux to control the state(data) of app on front-end level. To make a central source of truth to whom we can trust for our state we have made a redux 'STORE' in which have 2 things :

1) State of the application. 2) Reducer (Which contains our all Actions' definitions).

Suppose our two components or pages are using value of the state and one of them for instance say Page 1 : wants to increment the value of count by 1. So Page 1 will dispatch an 'action' towards 'reducer ' to do it so. Then reducer will find if he got definition of increment action and if it founds that he do the same to the central state & emits its updated state. Other pages like Page 2, who have subscribed to its value will get updated about this value and will now show the updated value on their page. To understand this fully lets get started with React-redux app.

If you are new to react, you can look for my Github repository React CRUD for beginners where I have made 5 Lessons(Branches) in which you can learn "react' step by step with prerequisite of basic knowledge in JS. To install react you must have npm install in your system.

To install react : "npm install -g create-react-app"

To create react app : "create-react-app react-redux-app"

For installing redux in your app : "npm install --save redux react-redux"

DONT GET FRUSTRATED IF YOU DO NOT UNDERSTAND ANYTHING FURTHER FROM THIS POINT, I WILL CREATE A GITHUB REPO IN WHICH STEP BY STEP APPROACH WILL BE GIVEN WITH MULTIPLE LESSONS' (BRANCHES) WHERE YOU CAN UNDERSTAND HOW TO CONVERT REACT TO 'REACT-REDUX-APP' SMOOTHLY.

After Installing go to react-redux-app/src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
	

	

ReactDOM.render(
  <App />,document.getElementById('root'));

and react-redux-app/src/App.js

	import React, { Component } from 'react';
	

	class App extends Component {
	  render() {
	      return (
	      <div className="App">
	        <h1>Hello React!</h1>
	      </div>
	      );
	  }
	  }
	export default App;

Now in terminal run command : "npm start" . This will start your application and you fav. browser will open "localhost:3000" and shows you "Hello React".

Now we will first create a Store , /src/store/reducer.js

const initialState = {
  count: 1
};


const reducer = (state = initialState, action) => {
  const newState = { ...state };
  switch (action.type) {
    case "INC":
      return {
        ...state,
        count: state.count + action.value
      };


    case "DEC":
      return {
        ...state,
        count: state.count - action.value
      };


    default:
      break;
  }
  return newState;
};


export default reducer;

In this file , we have made an 'initialState' for our 'count' value and a 'reducer' function in which "INC" and "DEC" actions are defined. This actions are just updating the state.count value by value given in the argument.

Now /src/app.js

import React, { Component } from "react";
import "./App.css";
import { connect } from "react-redux";


class App extends Component {
  render() {
    return (
      <div className="App">
        <h3>Count : {this.props.count}</h3>
        <button onClick={this.props.handleINC}>Inc</button>
        <button onClick={this.props.handleDEC}>Dec</button>
      </div>
    );
  }
}


//subscriber
const mapStateToProps = state => {
  return {
    count: state.count
  };
};


//eventHandler(Action)
const mapDespachToProps = dispach => {
  return {
    handleINC: () => dispach({ type: "INC", value: 1 }),
    handleDEC: () => dispach({ type: "DEC", value: 1 })
  };
};


export default connect(
  mapStateToProps,
  mapDespachToProps
)(App);

This file has 5 main steps but to understand this concept you first must know 'High Order Components' which basically means pass one function to another function as an argument and set state in that function. To understand this concept fully, google it now.

1)  Get the subscriber so that we can show count value in our app.js component.

 //subscriber
const mapStateToProps = state => {
  return {
    count: state.count
  };
};

2) Show the value in render() method. All redux values comes in props only.

render() {
    return (
      <div className="App">
        <h3>Count : {this.props.count}</h3>
        <button onClick={this.props.handleINC}>Inc</button>
        <button onClick={this.props.handleDEC}>Dec</button>
      </div>
    );
  }





Till now we have made count value visible to our component but this will not work.

//eventHandler(Action)
const mapDespachToProps = dispach => {
  return {
    handleINC: () => dispach({ type: "INC", value: 1 }),
    handleDEC: () => dispach({ type: "DEC", value: 1 })
  };
};
Now Import {connect} from 'react-redux' to connect component our reducer.
export default connect(
  mapStateToProps,
  mapDespachToProps
)(App);
Above code-snippet will connect subscriber and dispatch to our main store(reducer) which is most important point to work with redux. This concept is HOC(high order component).

Now look for /src/index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

//Provider provides to store to our all components
import { Provider } from "react-redux";
//createStore is redux app to create store in our app from redux.
import { createStore } from "redux";

//importing our reducer in index.js
import reducer from "./store/reducer";


//creating store from createStore which takes reducer as argument.
const store = createStore(reducer);


ReactDOM.render(
//Here we are providing Provider with store prop to our app component so that 
//count will be available to it as a props.
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);


// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();


No alt text provided for this image

This is the result which will you see in your app on browser. I hope you guys understand something in this article and dont worry if anyone needs its step by step git repo I will update this article shortly with diff branches.

To view or add a comment, sign in

Explore content categories