The Wayback Machine - https://web.archive.org/web/20240930161002/https://www.geeksforgeeks.org/introduction-to-react-redux/
Open In App

Introduction to React-Redux

Last Updated : 06 Jan, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The ones familiar with react will know that react is a component-based front end library tool that connects the various segments of the web page. In react, we use props (short for properties) in a component which allows the usage of non-static variables. With the help of props, we can pass these variables into various other components (child components) from the parent component.

Example: Passing props from parent component to child component: 

Javascript




import React, { Component } from 'react';
class App extends Component {
  render() {
    const wishes = 'Welcome to My World';
    return (
      <div>
        <Greeting wishes={wishes} />
      </div>
    );
  }
}
class Greeting extends Component {
  render() {
    return <h1>Welcome to {this.props.wishes} world!!</h1>;
  }
}
export default App;


The presence of the state in react allows defining its own variables of a component. With a few components in our application, we can pass these states as props to the child components. But as the count of components increases in the application in accordance with its large objective, we need to pass these state to other components located far away from each other in the component tree. At this moment, the usual way of transferring state as props turns out to be complex as not every component is a parent to the component requiring the state.

Example: Initializing state in a component and passing it as props to its child component:  

Javascript




class Parent extends Component{
 constructor(props){
  super(props);
  this.state={
   child1=0;
   child2=1;
  };
 }
 render()
 {
  return (
   <Child1 value={this.state.child1} />
   <Child2 value={this.state.child2} />
  );
 }
}


This brings the need for react-redux in our react application. React-redux being a state management tool makes it easier to pass these states from one component to another irrespective of their position in the component tree and hence prevents the complexity of the application.

Working Procedure: When a react application holds various components in need of state from other components it becomes difficult to realize where the state should reside among these components to make it easier to maintain. React-redux provides a store which makes the state inside components easier to maintain. Along with stores, react-redux introduces actions and reducers which work simultaneously with stores to make the state more predictable. The working of the features in react-redux is explained below: 

  • Store: It contains the state of the components which need to be passed to other components. The store makes this passing along much easier as we no longer need to maintain a state inside a parent component in order to pass the same to its children components.
  • Actions:The actions part of the react-redux basically contains the different actions that are to be performed on the state present in the store.The actions included must contain the type of the action and can also contain payload(data field in the actions).
    Example: Actions of increment and decrements in a react app: 

Javascript




export const increment = (num) => {
    return{
        type: 'INCREMENT',
        payload: num
    };
};
 
export const decrement = () => {
    return{
        type: 'DECREMENT',
    };
};


  • Reducers: The reducers in react-redux are the pure functions that contain the operations that need to be performed on the state. These functions accept the initial state of the state being used and the action type. It updates the state and responds with the new state. This updated state is sent back to the view components of the react to make the necessary changes. A reducer must contain the action type.
    Example: Reducer which updates the state in accordance with the action type 1st program and the 2nd program shows the snippet of creating the store which accepts the reducer.
    Program:1 

Javascript




const counterReducer = (state=0, action) => {
 switch(action.type)
 {
  case 'INCREMENT':
   return state + action.payload;
  case 'DECREMENT':
   return state - 1;
  default:
   return state;
 }
};


  • Program:2 

Javascript




import {createStore} from 'react-redux';
 
const store = createStore(
 counterReducer,
 window.__REDUX__DEVTOOLS__EXTENSIONS__ &&
    window.__REDUX__DEVTOOLS__EXTENSION__()
);


React-Redux needed for: As shown above, it is clearly noticeable that the usage of react-redux introduces a lot of boilerplate code in our application only for the purpose of passing the state from one component to the other. This may lead many new learners of react-redux to withdraw their interest from the same. Regardless of this fact many developers prefer react-redux in their application due to the following reasons: 

  • Reduces code complexity: As discussed earlier, when an application holds a large number of components interacting with each other through their state it becomes difficult to manage the passing of state of a component as props to another component located far in the component tree. React-redux with the introduction of the store holds the state of the application’s components and hence makes the code simpler as it removes the confusion of where the state should have resided.
  • Easier Maintainability: With the help of the store, the state is now located at one position in the application which makes it easier to maintain whenever an update in the state takes place in various components.
  • Reduces Time: React-redux refreshes the parts of a page rather than reloading the whole page and therefore saves us time.
  • Effortless Debugging: React-redux introduces reducers which are pure functions operating on the state which makes the logic simpler and helps in achieving effortless debugging.

Installing: To install react-redux in your react app, run the below command in the terminal:  

npm install react-redux

Reference: https://react-redux.js.org/
 



Similar Reads

Benefits of using React-Redux over plain Redux
React-Redux streamlines state management in React applications by integrating seamlessly with Redux, eliminating prop drilling. It enhances predictability and scalability through centralized state management and facilitates the creation of reusable UI components. This integration optimizes syntax, approaches, and implementation steps, offering a ro
5 min read
How Redux Toolkit simplifies Redux code in React application ?
Redux Toolkit is a powerful library designed to simplify the complexities of managing application state with Redux in React applications. At its core, Redux Toolkit provides developers with a set of utilities and abstractions that significantly reduce boilerplate code and streamline common Redux tasks. This means that developers can focus more on b
5 min read
Why Redux Toolkit is preferred over Redux ?
While working as a Front-end Developer or Full Stack Developer, many engineers encountered Redux. But Recently Redux Team launched Redux Toolkit(RTK), an officially recommended SOPE library that stands for Simple, Opinionated, Powerful, and Effective state management library. It allows us to write more efficient code, speed up the development proce
4 min read
Redux Toolkit Better way to write Redux code in ReactJS
Redux Toolkit is used for writing redux code but in a more concise way. Redux Toolkit (RTK) solves three bigger problems that most of the developer's face who used redux in a react application. Too much code to configure the store.Writing too much boilerplate code to dispatch actions and store the data in the reducer.Extra packages like Redux-Thunk
4 min read
Redux Thunk vs. Redux Saga: Choosing the Right Middleware
Redux, a predictable state container for JavaScript apps, is widely used in React applications for managing application state. Redux Thunk and Redux Saga are middleware libraries commonly employed with Redux for managing side effects such as asynchronous API calls, complex state transitions, and more. Both offer solutions for handling asynchronous
3 min read
How does Redux Saga Differ from Redux Thunk ?
In Redux, middleware plays a crucial role in managing asynchronous actions. Redux Saga and Redux Thunk are two popular middleware libraries used for handling side effects in Redux applications. While both serve similar purposes, they differ significantly in their approach and capabilities. In this article, we'll see the differences between Redux Sa
5 min read
How does Redux Toolkit simplify Redux development?
Redux is a powerful state management library for JavaScript applications, but setting it up and managing boilerplate code can be cumbersome. Redux Toolkit is an official package from the Redux team designed to streamline Redux development and reduce boilerplate code. In this article, we'll explore how Redux Toolkit simplifies Redux development and
6 min read
In what scenarios might you choose Redux Thunk over Redux Saga, and vice versa?
Redux, a predictable state container utilized in JavaScript applications, is extensively employed in React applications to manage application state. Middleware libraries like Redux Thunk and Redux Saga are commonly integrated with Redux to handle side effects such as asynchronous API calls and intricate state transitions. While both offer solutions
4 min read
How to Migrate an Existing Redux Application to Redux Toolkit?
Migrating an existing Redux application to Redux Toolkit (RTK) can streamline your Redux code, reduce boilerplate, and improve maintainability. Here's a step-by-step guide to help you through the migration process. Prerequisites:ReduxReactJSJavaScriptSteps to Create Redux ApplicationStep 1: Create a React Application named 'redux-migration-demo' an
4 min read
What is the use of React Context in React-Redux?
React Context is a feature that React provides us to manage states required in multiple components. Redux is also a state management library and solves the same problem that React Context does but in a different way. In this article, we will see in detail what is react context, why and how to use it, how it is related to and different from react-re
5 min read
Implementing React Router with Redux in React
This article explores implementing React Router with Redux for enhanced state management and routing in React applications. Table of Content What is React Router and Redux?Approach to implement React Router in ReduxSteps to Setup the React AppWhat is React Router and Redux?React Router facilitates routing in React apps, managing component rendering
3 min read
How to use React Context with React-Redux ?
React context with React-Redux is a popular state management library for React applications. Using React context with React-Redux is a powerful way to provide the Redux store to components deep within your component tree without manually passing it down through props. PrerequisitesNode.js and NPMReactReact-ReduxJavaScriptApproach:First, define a Re
3 min read
Introduction to Redux (Action, Reducers and Store)
Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React.Uses: It makes easier to manage state and data. As the complexity of our application increases. At the start, it is hard to understand bu
4 min read
Redux Store in React Native
In this article, we are going to learn about Redux Store. It is the object which holds the state of the application. The store is one of the building blocks of Redux. Redux is a state managing library used in JavaScript apps. It is used to manage the data and the state of the application. Uses of Redux: With the help of redux it is easy to manage s
5 min read
What's the typical flow of data like in a React with Redux app ?
Redux is an open-source state management JavaScript library for managing the application state. It is popularly used in ReactJS, but is not limited to it, and can also be used with other JavaScript libraries such as Angular. In a conventional React-Redux application, there is a single store along with a single root reducer. As the application grows
5 min read
Comparing Redux and Context API in React: A Comprehensive Analysis
In this article, we are going to learn about the difference between the Redux and Context APIs. We will cover each of them entirely with their live examples, and then we will cover the differences between them. Table of Content Context APIReduxDifference between Redux and Context APIConclusionContext APIInstead of manually passing props down at the
5 min read
Implementation of Dark Mode in React using Redux Toolkit
In this article we are going to implement Dark and Light mode toggle button using React JS and Redux Toolkit. Dark Mode is also known as night mode. It is just a dark theme where mostly background colors will turn into dark and text color will turn into light. Preview of final output: Let us have a look at how the final output will look like. Prere
3 min read
State Management in React – Hooks, Context API and Redux
While developing a React Application, it is very important to manage the state efficiently for building fully functional applications. As React is growing there are multiple approaches introduced that can help to manage state efficiently depending upon the type of application we are building. We will discuss the following state management technique
6 min read
What is the motivation for using React Redux?
React Redux makes handling data in big applications easier. It acts like a connection between different parts of your app (React components) and a central place where all the important data is stored (Redux). This ensures everyone is working with the same up-to-date information, making your app organized and development smoother. Features of React
2 min read
What are the benefits of using hooks in React-Redux?
Have you ever wondered how users create amazing websites and apps? Well, in the world of programming, they have some cool tools, and today we're going to explore one of them called "Hooks" in the superhero team of React-Redux. Prerequisites:ReactReact-ReduxReact HooksJavaScriptWhat are Hooks?Hooks are functions and essential mechanisms that optimiz
2 min read
What are Providers in React Redux?
AdvantagesProvider is like a supervisor for your Redux store. It's a special component provided by the React Redux library that wraps around your entire React application. This Provider component ensures that all components inside your app can access the Redux store and its state without having to pass it down manually through component props. Prov
2 min read
Write an overview of React Redux
React Redux is like a helper for your React application. It provides the way of communication link between the React and Redux. It helps them to talk smoothly. So, when you're building your app with React, and you need to grab some ingredients from the store (Redux), React Redux is there to help you out. In this, we will see the overview of React R
3 min read
What are combinedReducers in React Redux?
In React Redux 'combinedReducers' is like putting together smaller pieces of a puzzle (reducers) to form one big puzzle (the root reducer). It helps manage your application state more efficiently by organizing and combining these smaller pieces, making your code cleaner and easier to maintain. Key Features of combinedReducers in React Redux:Organiz
3 min read
Explain Connect() function in React Redux.
The connect() function in React Redux is used to connect the React components with the Redux store. It is a higher-order component provided by the React Redux library that allows you to access the state of Redux and then dispatch the action without worrying about how the Redux works. Syntax:function connect(mapStateToProps?, mapDispatchToProps?, me
2 min read
Explain Selectors in React Redux
Selectors in React Redux serve as efficient filters for accessing specific data from the Redux store. They encapsulate logic for data retrieval, optimizing performance, and promoting code reusability. By using memoization, selectors cache results to prevent unnecessary re-renders, thus enhancing overall application efficiency. They make efficient i
2 min read
Explain the concept of error boundaries in React-Redux.
Error boundaries in React-Redux are components that catch errors within their child component tree, preventing the entire app from crashing. They display a fallback UI when an error occurs, improving user experience by gracefully handling errors. Error boundaries can be implemented around connected components, helping isolate and manage errors with
2 min read
Extracting Data with mapStateToProps in React Redux
'mapStateToProps' is a function used to extract data from the Redux store and pass it as props to a React component. It allows you to specify which parts of the Redux store state you want to access within your component. The data extracted using mapStateToProps is injected into the component as props, making it available for use within the componen
2 min read
Presentational and Container Components in React Redux
React Redux is a library that simplifies state management in React applications by providing a centralized store where data can be stored and accessed from any component. It helps keep your code organized and efficient, especially in large-scale projects where the managing state becomes more complex. With React Redux, you can easily connect your Re
2 min read
React Redux Interview Questions And Answers
Redux is one of the most popular state management libraries used today for building a complex application that requires global state management. In this article, you will learn the top Redux interview questions and answers that are most frequently asked in interviews. Before proceeding to learn Redux interview questions and answers, it is beneficia
15+ min read
What is Logger middleware in React Redux ?
Logger middleware is a tool that helps users understand what's happening behind the scenes in their Redux-powered React applications. It logs information about each action that gets dispatched in your app, along with the state before and after the action is processed. Syntax:import { createStore, applyMiddleware } from 'redux';import logger from 'r
3 min read