DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Building a Full-Stack Resume Screening Application With AI
  • Common Problems in React Native Apps on iOS Platform: Solutions and Tips
  • Adding a Gas Station Map to a React and Go/Gin/Gorm Application
  • Choosing the Right Framework for Your Project

Trending

  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Docker Base Images Demystified: A Practical Guide
  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • The Modern Data Stack Is Overrated — Here’s What Works
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Connect Your React Application With Redux

How to Connect Your React Application With Redux

Learn how to better manage the state of your React.js application by using Redux.

By 
Kritika Saxena user avatar
Kritika Saxena
·
Updated Jan. 17, 20 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
24.0K Views

Join the DZone community and get the full member experience.

Join For Free

An exciting adventure for React developers is when they connect their React application with redux and when you have made it this far in reading about React, that means you are on the way to explore the out of the box concept of how you can manage global states in your application. This article will be helpful for React developers in integrating React applications with Redux.

Though React gives us the ability to manage state for our components, the dependency of the parent components on the child components and state management between two components becomes complicated with the increasing size of the application. To resolve this issue we have a third-party library called Redux which gives us all these wonderful features we need for global state management. Read Further at React Application with Redux.

Redux is a third-party JavaScript library which is used for the global state management of your application. It can be used with any front-end JavaScript Framework like React, Angular, Vue, Ember and many more but most often it is used with React.

It provides us a way to manage our state in one place with the help of the concepts like Reducer, Action, and Store.

We will create a basic React.js project and go through integrating Redux step-by-step.

Project Setup

Now the first thing to do is to create a React Project so that we can use our Redux library there. We can do this by using create-react-app. 

Must Read: The Common Mistakes in React Development & How can you Avoid them?

Go to your terminal and type in the commands:

React commandsNow your sample React project will be up and running on localhost:3000

This is a simple React application setup where you will have all the basic dependencies for your React app. To connect your React component with the Redux Store we need to install some libraries and those libraries are:

  • Redux | Command
  • React-Redux | Command

Creating a Store and Connecting it With the Component

Where do we create a store? Well for me it is always at index.js because there we have the very root component App from where we can pass on the States from the Store.

So the first thing we do here is to create Store and for that we will import

And then we will create a Store

As we need to pass reducer on createStore(), we will be creating a Reducer file where we will define our actions.

Reducer.js | Basic

Here we created a basic reducer with state which is returning the state as it is.

Now we need to connect our store to our React application and we want to get access to the state in our component so that we do something useful.

Let’s connect our Store here with the Component.

Because Redux is an independent library and we need to connect it with React, we will be importing Provider from the react-redux library inside the same index.js file.

And now we need to wrap the Root component (which is <App /> in our case) with the Provider. It allows us to pass our store which contains the state into the React component. You can pass it the same way you pass the properties in the React component.

We will pass it with the property name store and passing the information coming from our Reducer which we have also named as store.

App.js File

This file is responsible for all the UI element. On this page we will be performing our basic tasks like Increment, decrement, add, substract, reset. Now I have used bootstrap here to create some UI element but will not be discussing it in this article since this is not in the scope of our topic.

importReact, { Component } from'react';
import'./App.css';
import { connect } from'react-redux'
import { Container, Card, Button,Row,Col } from'reactstrap'

classAppextendsComponent {
state = {
info :''
}
render() {
return (

<ContainerclassName="mt-5">

<div>

<Cardstyle={{"width":"350px" , "margin" :"0 auto" , "float" :"none", "marginBottom":"10px"}}>

<Card><pclassName="text-center mt-2">{this.props.value}</p></Card>

<RowclassName = "mt-3">

<Colmd="6"xs="6"sm="6"style={{"textAlign" :"right"}}>

<ButtonclassName="ml-1"onClick={()=>this.props._onInc()}>Increment</Button>

</Col>

<Colmd="6"xs="6"sm="6">

<ButtonclassName="ml-1"onClick={()=>this.props._onDec()}>Decrement</Button>

</Col>

</Row>

<RowclassName = "mt-1">

<Colmd="6"xs="6"sm="6"style={{"textAlign" :"right"}}>

<ButtonclassName="ml-1" >

</Col>

<Colmd="6"xs="6"sm="6">

<ButtonclassName="ml-1"style={{"width":"104px"}}onClick={()=>this.props._onSub()}>Subtract 3</Button>

</Col>

</Row>

<RowclassName = "mt-1 text-center">

<Colmd="12"xs="12"sm="12">

<ButtonclassName="ml-1 mb-2"onClick={()=>this.props._onReset()}>Reset</Button>

</Col>

</Row>

</Card>

</div>

</Container>
);
}
}

constmapStateToProps = (state) =>{
return {
state :state
}
}

constmapDispatchToProps = (dispatch) =>{
return{
      _onInc : () =>{
dispatch({
type :"ON_INCREMENT",
value :1
})
},
_onDec : () =>{
dispatch({
type :"ON_DECREMENT",
value :1
})
},
_onAdd : () =>{
dispatch({
type :"ON_ADD",
value :3
})
},
_onSub : () =>{
dispatch({
type :"ON_SUBTRACT",
value :3
})
},
_onReset : () =>{
dispatch({
type :"ON_RESET",
value :0
})
  }
   }
}

exportdefaultconnect(mapStateToProps,mapDispatchToProps)(App);

So far, we don’t have access to our store directly inside the component. For this, we need to connect our component with the Store by importing connect from react-redux.

import { connect } from'react-redux' 

connect is a method which returns a function which then takes a component as an input. So, in short, it’s a function that returns a higher order component, and, since connect is a function, we can pass the argument as the configuration for the component.

Basically, we pass two arguments:

  • The exact state we want.
  • The action wewant to dispatch.

mapStateToProps

Now we want to get state and for that we will declare a constant after the class declaration. Here we will map the state which is stored at store to the props

constmapStateToProps = (state) =>{
return {
value:state.value
}
}

We have called this state as props (named as value) in our application above. The state here is the same state (global state) we have defined in the reducer.

<Card><pclassName="text-center mt-2">{this.props.value}</p></Card>

mapDispatchToProps

Here we can define which kind of action we can dispatch. It will receive dispatch as an argument and where it will return a JavaScript Object on which we can dispatch an action which has information like type and value (payload).

constmapDispatchToProps = (dispatch) =>{
return{
_onInc : () =>{
dispatch({
type :"ON_INCREMENT",
value :1
})
}
}
}  

Reducer.js File 

Here we have defined different cases for different actions that we are performing in the App.js file and this again can pass the updated states to the store and then the store will be available to all of our components through connect (react-redux).

If you have any questions that remains unanswered, then this tutorial on React can be really helpful.

In the beginning, Redux can be little complex to understand but at the same time this is one of the most powerful tools for React to manage your state. Hire react developer that will give you extra power to develop your application in a smarter way.



If you enjoyed this article and want to learn more about React, check out this collection of tutorials and articles on all things React.

React (JavaScript library) application

Published at DZone with permission of Kritika Saxena. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building a Full-Stack Resume Screening Application With AI
  • Common Problems in React Native Apps on iOS Platform: Solutions and Tips
  • Adding a Gas Station Map to a React and Go/Gin/Gorm Application
  • Choosing the Right Framework for Your Project

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!