Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to use HOCs to reuse Component Logic in React ?
Next article icon

How to connect the components using Connect() in React Redux

Last Updated : 04 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In React Redux, you use the connect() function to connect your components to the Redux store. This function takes two parameters: mapStateToProps and mapDispatchToProps. mapStateToProps maps the store's state to the component's props, while mapDispatchToProps maps dispatch actions to props. By using connect( ), your components can access the store's state and dispatch actions easily.

Output Preview: Let us have a look at how the final output will look like.

cdw

Prerequisites

  • NodeJS NPM
  • ReactJS
  • React Hooks
  • JSX

Approach

  • Initialize a new React project (Counter) using Create React App. Install necessary dependencies such as redux, react-redux, and any additional packages required for your project.
  • Create a directory structure for Redux-related files, define your actions , reducers, creating store etc.
  • Design the component hierarchy based on your application's requirements. Create React components for UI elements, organizing them into appropriate folders (e.g., src/components). Ensure each component is designed to be reusable and focused on a single responsibility.
  • Connecting Components to Redux: This is the most crucial part of state management. Here importing react-components, Defining mapStateToProps function, mapDispatchToProps function such work is done. Use connect() to connect components to the Redux store, passing in mapStateToProps and mapDispatchToProps as arguments is also done here.

Steps to create application

Step 1: Create a reactJS application by using this command

npx create-react-app my-app

Step 2: Navigate to project directory

cd my-app

Step 3: Install the necessary packages/libraries in your project using the following commands.

npm install react react-dom redux react-redux

Project Structure:

1711282615926
Counter Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"redux": "^4.1.2",
"react-redux": "^7.2.6"
}

Example: Implementation to showcase how to connect the components using connect method in react redux.

CSS
/* style.css */  body {     margin: 0;     display: grid;     place-items: center;     height: 100vh; }  img {     margin-left: 80px; }   button {     border-radius: 8px;     border: 1px solid transparent;     padding: 0.6em 1.2em;     font-size: 1em;     font-weight: 500;     font-family: inherit;     cursor: pointer;     margin: 10px;     transition: border-color 0.25s; }  p {     text-align: center; }  button:hover {     border-color: #646cff; } 
JavaScript
// Counter.js  import React from 'react'; import { connect } from 'react-redux'; import { increment, decrement } from './store';  const mapStateToProps = (state) => ({   count: state.counter, });  const mapDispatchToProps = {   increment,   decrement, };  const ConnectedCounter = ({ count, increment, decrement }) => (   <div>     <p id='count'>Count: {count}</p>     <button onClick={increment}>       Increment     </button>     <button onClick={decrement}>       Decrement     </button>   </div> );  export default connect(mapStateToProps, mapDispatchToProps)(ConnectedCounter); 
JavaScript
// store.js   import { createStore } from 'redux';   // actions export const increment = () => ({     type: 'INCREMENT', });  export const decrement = () => ({     type: 'DECREMENT', });   // counterReducer const initialState = {     counter: 0, };  const counterReducer = (state = initialState, action) => {     switch (action.type) {         case 'INCREMENT':             return { ...state, counter: state.counter + 1 };         case 'DECREMENT':             return { ...state, counter: state.counter - 1 };         default:             return state;     } };   // store const store = createStore(counterReducer);  export default store; 
JavaScript
// index.js   import React from 'react'; import ReactDOM from 'react-dom/client'; import { Provider } from 'react-redux' import './style.css' import store from './store'; import Counter from './Counter';  const root = ReactDOM.createRoot(document.getElementById('root')); root.render(   <Provider store={store}>     <div id='wrapper' >       <div id='header' >         <img src='https://media.geeksforgeeks.org/gfg-gg-logo.svg'               alt='gfg_logo' />         <h2 id='todo_banner'>             GFG Counter Project         </h2>       </div>       <Counter />     </div>   </Provider> ); 

Output:
cdw


Next Article
How to use HOCs to reuse Component Logic in React ?

S

sandeepxt99
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Redux

Similar Reads

  • How do you optimize the rendering of connected components in React-Redux?
    React-Redux is a powerful combination for building complex web applications, particularly those with dynamic user interfaces. However, as applications grow in size and complexity, rendering performance can become a concern. Optimizing the rendering of connected components in React-Redux is crucial f
    3 min read
  • How to conditionally render components in ReactJS ?
    React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook. PrerequisitesNodeJS or NPMReact JSReact
    3 min read
  • Methods to Optimize the re-render in React-Redux Connected Component?
    For a smooth user experience, fast rendering in React applications is crucial. Using React-Redux can sometimes lead to performance issues due to unnecessary re-renders of connected components. This article will explore several methods to avoid the rendering of these components. By implementing these
    4 min read
  • How to use HOCs to reuse Component Logic in React ?
    In React, making reusable components keeps your code neat. Higher-order components (HOCs) are a smart way to bundle and reuse component logic. HOCs are like magic functions that take a component and give you back an upgraded version with extra powers or information. HOCs can be implemented in a few
    4 min read
  • How to Integrate Redux with React Components ?
    Redux is an open-source JavaScript library for managing and centralizing application state. It helps you to write applications that behave consistently and are easy to test and run in different environments. It can also be understood as the predictable state container for the JavaScript app. It is m
    4 min read
  • How to create components in ReactJS ?
    Components in React JS is are the core of building React applications. Components are the building blocks that contains UI elements and logic, making the development process easier and reusable. In this article we will see how we can create components in React JS. Table of Content React Functional C
    3 min read
  • How to create Functional Components in React ?
    To create a functional component in React, you define a JavaScript function that returns JSX. These components are stateless and rely on props for data input. Functional components are concise, easy to read, and can utilize React Hooks for managing state and side effects, making them a fundamental b
    2 min read
  • How to Map Data into Components using ReactJS?
    Mapping data in react js component is a comman practice to render the lists and repeating elements. In this article, we will have a users data and we will map it to react components to display the users information in the react app Prerequisites:React JSNodejs and npmJavaScript Array mapApproachTo m
    3 min read
  • How to convert functional component to class component in ReactJS ?
    ReactJS offers two primary ways of creating components: functional components and class components. While functional components are more concise and easier to reason about, there are situations where class components may be necessary with the flexibility to use lifecycle methods and manage the state
    2 min read
  • How to pass data into table from a form using React Components ?
    React JS is a front-end library used to build UI components. This article will help to learn to pass data into a table from a form using React Components. This will be done using two React components named Table and Form. We will enter data into a form, which will be displayed in the table on 'submi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences