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.

We will cover the following topics in this React With Redux tutorial:

  • Why Redux?
  • What is Redux?
  • Principles of Redux
  • Pillars of Redux
  • Pros and Cons of Redux
  • Demo application:
    • React application without Redux
    • React application with Redux

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

Master the fundamentals of React including JSX, props, state, and events. Consider the React.js Certification Training Course. Enroll now!

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.

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 

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.

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

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.

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

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.

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. 

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 React.js Training Course. 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

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

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