React With Redux Tutorial: Learn the Basics

React is the most popular front-end JavaScript library available today. From startups to large corporations, more companies are adopting this widely used technology. Well-known brands like Netflix, Airbnb, and The New York Times are using it for their websites and their mobile applications.

Redux is a predictable state container for JavaScript apps. As an application grows, it becomes difficult to keep it organized and maintain data flow. That is where Redux comes to the rescue.

This React with Redux article will help you gain a working understanding of the basic concepts of this popular technology. For starters, we’ll get familiar with some of the basic Redux concepts. Once we’re done, we will create a simple React application with Redux, then an application without it. This exercise will clearly show the difference between the two implementations.

Now before we get into the depths of understanding React with Redux, let us first understand why Redux!

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

Why Redux?

State transfer between components is pretty messy in React since it is hard to keep track of which component the data is coming from. It becomes really complicated if users are working with a large number of states within an application.

redux

Redux solves the state transfer problem by storing all of the states in a single place called a store. So, managing and transferring states becomes easier as all the states are stored in the same convenient store. Every component in the application can then directly access the required state from that store.

Also Read: Top 10 Reasons to Learn JavaScript

What is Redux?

Redux is a predictable state container for JavaScript applications. It helps you write apps that behave consistently, run in different environments (client, server, and native), and are easy to test. Redux manages an application’s state with a single global object called Store.

redux1

Redux is a state management tool 

redux2.

Redux can be used with any JavaScript framework or library

redux3

Redux stores the state of the application, and the components can access the state from a state store

Principles of Redux

The three most important Redux principles are:

  • Single Source of Truth 

The state of your whole application is stored in an object tree within a single-store.

state-tree
  • A single state tree makes it easier to debug or inspect an application

  • It gives you a faster development cycle by enabling you to persist in your app's navigation state
  • State Is Read-Only

The only way to change the state is to initiate an action, an object describing what happened.

read
  • This feature ensures that no events like network callbacks or views can change the state. They can only express an intent to change the state

  • Actions are just plain objects; they can be logged, serialized, stored, and later replayed for debugging or testing purposes
  • Changes are Made with Pure Functions

To specify how actions transform the state tree, you need to write pure reducers.

user
  • The user can return new state objects instead of mutating the previous state
  • The user can start with a single reducer, and, as the app grows, can split it off into smaller reducers that manage specific parts of the state tree
  • Because reducers are just functions, it’s easy to control the order in which they are called, pass additional data, or even make reusable reducers 

Prepare Yourself to Answer All Questions!

Automation Testing Masters ProgramExplore Program
Prepare Yourself to Answer All Questions!

Pillars of Redux

These are Redux’s main pillars:

  • Store

A store is an object that holds the application's state tree. There should only be a single store in a Redux app, as the composition happens at the reducer level.

getState() returns the current state of the store.

dispatch() dispatches an action. It is the only way to update the application state.

button

subscribe() subscribes a change listener to the state.

unsubscribe() is useful when you no longer want to call your listener method when the state changes.

unsubs

  • Action

An action is a plain object that represents an intention to change the state. They must have a property to indicate the type of action to be carried out.

  • Actions are payloads of information that send data from your application to your store.
  • Any data, whether from UI events or network callbacks, needs to eventually be dispatched as actions.
  • Actions must have a type field, indicating the type of action being performed.
  • Reducers

Reducers are pure functions that specify how the application's state changes in response to actions sent to the store.

  • Actions only describe what happened, not how the application's state changes.
  • A reducer is a function that accepts the current state and action, and returns a new state with the action performed.
  • combineReducers() utility can be used to combine all the reducers in the app into a single index reducer which makes maintainability much easier.

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

Pros and Cons of Redux

Pros

pro

There is always one source of truth, the store. Thus, there is no confusion about how to sync the current state with actions and other parts of the application.

pro2

The code is easier to maintain because it has a predictable outcome and strict structure.

pro3.

Redux makes coding more consistent due to more stringent code organization procedures

pro4

It’s very useful, especially during the initial render, making for better user experience and search engine optimization.

pro5

Developers can track everything going on in the app in real-time—from actions to state changes

Cons

con-1

Since it has no encapsulation, any component can access data, which may potentially cause security issues

con-2

Some parts of the code are just boilerplate. However, these parts have to be incorporated with no alteration, and this restricts the design

con-3

As the state is immutable in Redux, the reducer updates the state by returning a new state every time which can cause excessive use of memory

Demo Application: React with Redux

In this demo, we will create a web application in two ways:

  1. Web Application without Redux (Normal working with the use of State objects)
  2. Web Application with Redux (Using Store and reducers)

The goal of this application is to display a subscribe button along with a message reading “Subscribe to Simplilearn.” Once the user clicks on the button, the message changes to “Thank you for subscribing.” So first let’s start by building the application without Redux. Later on, we will look into Redux implementation. As we work through both designs, note the differences.

Unleash a High-paying Automation Testing Job!

Automation Testing Masters ProgramExplore Program
Unleash a High-paying Automation Testing Job!

Web Application without Redux

1. Create a component called NewComp with the following code and export the component to the main component. The component NewComp.js reads the following code: 

import React, { Component } from "react";

import { connect } from "react-redux";

class NewComp extends Component {

  constructor(props) {

super(props);

 

this.state = {

   message: "Subscribe to Simplilearn"

};

  }

  styles = {

fontStyle: "italic",

color: "purple"

  };

  Buttonchange = () => {

this.setState({

   message: "Thank you for subscribing"

});

  };

 

  render() {

return (

   <div className="App">

     <h3 style={this.styles}>{this.state.message}</h3>

     <button onClick={this.Buttonchange}>Subscribe</button>

   </div>

);

  }

}

  • In this component, we first initialize the state with the message set as “Subscribe to Simplilearn”
  • We then set the style of text using a styles keyword
  • After setting the style, we create an arrow function that changes the state of the message to “Thank you for subscribing”
  • Finally, we define a render method that renders the state on-screen along with the button

2. Import the component NewComp into the main component App.js. The App.js main component reads the following code: 

import React from "react";

import "./App.css";

import NewComp from "./Components/NewComp";

class App extends React.Component {

  styles = {

fontStyle: "bold",

color: "teal"

  };

  render() {

return (

   <div className="App">

     <h1 style={this.styles}> Welcome </h1>

     <NewComp />

   </div>

);

  }

}

export default App;

  • Create the main component App.js 
  • Import NewComp into this file
  • Define the styles for text
  • Define the render() method that returns Welcome on the screen along with the content of NewComp that we imported before

3. The application, when run, should like this:

welcome1

welcome2

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Web Application with Redux

1. Create a store in the index.js file 

import React from "react";

import ReactDOM from "react-dom";

import "./index.css";

import App from "./App";

import * as serviceWorker from "./serviceWorker";

import { Provider } from "react-redux";

import { createStore } from "redux";

import reducer from "./Store/Reducer";

const store = createStore(reducer);

ReactDOM.render(

  <Provider store={store}>

<App />

  </Provider>,

  document.getElementById("root")

);

serviceWorker.unregister();

  • Import the necessary modules needed for implementing Redux in a React application
  • Create a constant store with “reducer” as the function parameter
  • Set the Provider to store and enclose the App component within it

2. Create a component called NewComp.js with the following code: 

import React, { Component } from "react";

import { connect } from "react-redux";

class NewComp extends Component {

  styles = {

fontStyle: "italic",

color: "purple"

  };

 

  render() {

return (

   <div className="App">

     <h3 style={this.styles}>{this.props.message}</h3>

     <button onClick={this.props.Buttonchange}>Subscribe</button>

   </div>

);

  }

}

 

const mapStatetoProps = state => {

  return {

message: state.message

  };

};

 

const mapDispatchToProps = dispatch => {

  return {

Buttonchange: () => dispatch({ type: "Message_change" })

  };

};

export default connect(

  mapStatetoProps,

  mapDispatchToProps

)(NewComp);

  • Define the styles for the text
  • Define the render() method that returns the text on the screen along with the Subscribe button
  • As the name suggests, the mapStatetoProps() method maps the state to Props so the component can access it

3. Create a folder called Store and a JavaScript file called Reducer.js within it with the following code:

const initialState = {

  message: "Subscribe to Simplilearn"

};

 

const reducer = (state = initialState, action) => {

  const newState = { ...state };

  if (action.type === "Message_change")

newState.message = "Thank you for subscribing";

  return newState;

};

export default reducer;

  • Define a constant initialState and set the message
  • Once the message is set, define a reducer arrow function which changes the state when it encounters a relevant action type

4. Finally, import the NewComp component in the main component App.js.

import React from "react";

import "./App.css";

import NewComp from "./Components/NewComp";

class App extends React.Component {

  styles = {

fontStyle: "bold",

color: "teal"

  };

  render() {

return (

   <div className="App">

     <h1 style={this.styles}> Welcome </h1>

     <NewComp />

   </div>

);

  }

}

export default App;

  • This component will be very similar to the app component that we implemented in the previous method
  • We set the styles for the on-screen text
  • The render method returns the Welcome text, along with the contents of the NewComp component that we imported in this file

There’s practically no noticeable difference between the output of both implementations. The difference, however, is in how each implementation manages the states in the web application.

We have now created a React web application using both methods. React with Redux is more effective with larger React applications and should not be used for small or simple React web applications. This is one of the commonly asked topics in the ReactJS interview questions

In case you have any questions related to this article, feel free to use our comments section and we will be more than happy to help. 

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Want to Learn More?

For more in-depth training on this increasingly popular web and mobile application development framework, upskill in web and mobile software development with Simplilearn’s Full Stack Developer - MERN Stack. Through a combination of self-paced and instructor-led online training, you will learn everything you need to know to kickstart your career in React-based development!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.