Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Angular

    How to Upload Images to a Cloud Storage(Imgur) in an Angular Application

    Programming

    Уроки React. Урок 4. Домашнее Задание.

    Programming

    Python map() Function Explained & Visualized

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, November 12
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / React / React Lessons / React Lesson 7: Redux
    JavaScript

    React Lesson 7: Redux

    Mohammad Shad MirzaBy Mohammad Shad MirzaJanuary 10, 2020Updated:February 9, 2020No Comments6 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    React Lesson 7: Redux
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    Today we’re going to learn Redux but first, we will complete the homework from the last lesson. Remember when we learned how to take help from the amazing world of Open-Source? This is one of those times. We are going to add the day picker module built and tested by the react community. Let’s get started.

    Install react-day-picker

    You can use either yarn or npm as convenient:

    yarn add react-day-picker

    Import module and CSS inside ArticleList

    import DayPicker, { DateUtils } from "react-day-picker";
    import "react-day-picker/lib/style.css";

    Update state

    DayPicker expects to and from value. Let’s add it to the state:

    state = {
      selectedArticles: null,
      from: undefined,
      to: undefined
    };

    Add DayPicker inside render:

    const { from, to } = this.state;
    const modifiers = { start: from, end: to };
    return (
      <div>
        <h1>Article list</h1>
        <Select
          options={options}
          isMulti={true}
          value={this.state.selectedArticles}
          onChange={this.handleSelectChange}
        />
        <DayPicker
          className="Selectable"
          selectedDays={{ from, to }}
          modifiers={modifiers}
          onDayClick={this.handleDayClick}
        />
        <ul>{this.renderListItem()}</ul>
      </div>
    );

    className add styling to the date picker. selectedDays expects you to pass from and to props to be shown on the calendar. Let’s add the handleSelectChange method to save user response.

    Add click handler

    handleDayClick = day => {
      const range = DateUtils.addDayToRange(day, this.state);
      const { from, to } = range;
      this.setState({ from, to });
    };

    Finally, add a small function to render day picker

    getRangeTitle() {
      const { from, to } = this.state;
      return (
        <p>
          {!from && !to && "Please select the first day."}
          {from && !to && "Please select the last day."}
          {from &&
            to &&
            `Selected from ${from.toLocaleDateString()} to
                  ${to.toLocaleDateString()}`}{" "}
          {from && to && (
            <button className="link" onClick={this.handleResetClick}>
              Reset
            </button>
          )}
        </p>
      );
    }
    
    //to reset date
    handleResetClick = () => {
      this.setState({ from: undefined, to: undefined });
    };
    
    //render getRangeTitle()
    render(){
      //...
      return(
          <div>
            <h1>Article list</h1>
            {this.getRangeTitle()}
            {/* previously added code...*/}
          </div>
      );
    }

    Let’s see how it looks:

    You can visit documentation for more information.

    We can see that our component state is getting more complex and we are losing atomicity. It means that one component should take one single task. We added Select and DayPicker together and this is the first sign we have to take care of State Management.
    With the increasing complexity of our app, it is very easy to introduce bugs because of poor state management. The React team offered a solution for logics building – Unidirectional Data Flow. So, let us see Redux working principles:

    Read More:  How to write effective tests for React apps with react testing library?

    Redux

    Redux is a predictable state container that supports the idea of a single source of truth. This simply means that the complete state of the application will reside in one place only.
    Redux is more focused on the concepts of functional programming and is inspired by Flux: A uni-directional way of updating Views and handling user actions.


    Concept

    As we can see in the image above. Redux consist of mainly 4 components. We will go through each of them and build a basic counter using redux. First, install the required modules:

    yarn add redux react-redux

    1. Store

    A store is just a container that contains the state of our whole application in an object tree. This is also called a “Single source of truth”. This makes debugging easier.

    Let’s create a new directory store and add an index.js file:

    import { createStore } from "redux";
    import reducer from "../reducers";
    
    const store = createStore(reducer);
    
    export default store;

    The store receives a reducer which we will see in a minute. But first, let’s see actions.

    2. Actions

    Another important concept is that the State is Read-Only. The only way to change the state is to emit an action, an object describing what happened. In short, actions are a piece of code that tells how to change state.
    Let’s create a new directory actions and write two actions inside index.js to increment and decrement the counter.

    import { INCREMENT, DECREMENT } from "../types";
    
    export const increment = () => {
      return {
        type: INCREMENT
      };
    };
    
    export const decrement = () => {
      return {
        type: DECREMENT
      };
    };

    Types are just to specify the type of action triggered. We will use it inside the reducer. I have defined types inside a different file to avoid misspelling.

    export const INCREMENT = "increment";
    export const DECREMENT = "decrement";

    3. Reducers

    Views cannot change the state DIRECTLY! It means the only way to update views is to trigger a state change inside reducer.
    In Redux, you dispatch actions. These actions tell a reducer to update the state. Redux docs also recommend not mutating the state. Each action instructs the reducer to replace the existing state with a new version.
    Let’s create a reducers directory and index.js file inside it.

    //import type constants
    import { INCREMENT, DECREMENT } from "../types";
    
    // state to begin with
    const INITIAL_STATE = {
      count: 0
    };
    
    // switch action based on types
    export default (state = INITIAL_STATE, action) => {
      switch (action.type) {
        case INCREMENT:
          return { ...state, count: state.count + 1 };
        case DECREMENT:
          return { ...state, count: state.count - 1 };
        default:
          return state;
      }
    };

    Reducers are just pure functions that return a new state every time we dispatch an action which in turn re-render the View.

    Read More:  Fames Acturpis Egestas Sed Tempus Etpharetra Pharetra

    4. View

    We need to access this state inside our component. Let’s see how we can do that:

    Step 1:

    Let’s create a component Counter to show count and trigger increment or decrement action.

    import React, { Component } from "react";
    import PropTypes from "prop-types";
    import { connect } from "react-redux";
    import { increment, decrement } from "../actions";
    
    class Counter extends Component {
      static propTypes = {
        count: PropTypes.number,
        increment: PropTypes.func
      };
    
      handleIncrement = e => {
        e.preventDefault();
        this.props.increment();
      };
    
      handleDecrement = e => {
        e.preventDefault();
        this.props.decrement();
      };
    
      render() {
        return (
          <div>
            <h1>{this.props.count}</h1>
            <a href="#" onClick={this.handleIncrement}>
              increment
            </a>
            <a href="#" onClick={this.handleDecrement}>
              decrement
            </a>
          </div>
        );
      }
    }
    
    const mapStateToProps = state => {
      return {
        count: state.count
      };
    };
    
    export default connect(
      mapStateToProps,
      { increment, decrement }
    )(Counter);

    We are using a connect function to connect our component with the store. Connect function is a Higher-Order component that adds extra functionality to our component. It receives few arguments.

    • One is mapStateToProps which let us access redux state inside the component.
    • The second argument is mapDispatchToProps which takes actions that we need to dispatch.

    Step 2:

    We have to wrap our whole application with Provider from ‘react-redux’ and pass the store. Update root file as:

    //add imports
    import Counter from "./components/Counter";
    import { Provider } from "react-redux";
    import store from "./store";
    
    function App() {
      return (
        <Provider store={store}>
          <Counter />
        </Provider>
      );
    }

    Our counter is ready. You can visit this codesandbox below to see the counter in action.

    Edit React_lesson_lesson7

    The lesson code can be found here.

    Снимок

    We are looking forward to meeting you on our website blog.soshace.com

    react redux
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Streamlining Resource Allocation for Enhanced Project Success

    December 18, 2024

    Conducting Effective Post-Project Evaluations: A Guide

    December 16, 2024

    Strategies for Keeping Projects on Track and Meeting Deadlines

    December 10, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Remote Job September 27, 2019

    Freelance Programming Is Great — but Is It for You?

    Becoming a freelancer isn’t simply a matter of “working from home” — it’s a new work paradigm that can really test your discipline and dedication.

    React Lesson 2: Homework Assignment

    November 1, 2019

    Top Lead Generation Strategies for MSPs in 2025

    May 3, 2025

    Hot Topics in Web Development | 12 Hottest Trends for 2019

    March 6, 2019

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Build Real-World React Native App #11 : Pay For Remove Ads

    JavaScript February 17, 2021

    Top 10 issues when hiring freelancers

    Remote Job September 28, 2018

    Guidelines to Writing a Clear Spec [Software Specification Document]

    Programming September 30, 2019

    Why Working Remotely Is a Double-Edged Sword

    Remote Job August 9, 2019

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    JavaScript

    Node.js Lesson 14: Asynchronous Development

    SEO & Analytics

    Effective Data Visualization Techniques for SEO Reporting

    JavaScript

    React Lesson 13 Part 2: Asynchronous actions

    Most Popular

    Google Algorithm Update: Recent Changes to SEO

    Beginners

    Uploading Files To Amazon S3 With Flask Form – Part1 – Uploading Small Files

    AWS

    Basic Principles and Rules of Our Team

    JavaScript
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.