DEV Community

Cover image for Building a React-Redux Counter: Understanding State Management with Redux in React
Remon Hasan
Remon Hasan

Posted on

Building a React-Redux Counter: Understanding State Management with Redux in React

Redux Counter

In this post we will take a look at using Redux for managing the state in React apps. For that we'll make a simple redux counter project. Let's break down each part of the Redux implementation step by step:

Source Code : Github

Redux Basics

Redux is a predictable state container for JavaScript apps. It helps manage the state of your application in a predictable way, making it easier to debug and understand how data changes over time.

Setting Up the Folder Structure

Actions

Actions are payloads of information that send data from your application to your Redux store. In the actions folder:

  • actionTypes.js: Defines action types as constants.

Image description

  • counterActions.js: Contains action creator functions that return actions.

Image description

Reducers

Reducers specify how the application's state changes in response to actions sent to the store. In the reducers folder:

  • counterReducer.js: Defines how the state for the counter should change based on dispatched actions.

Image description

  • index.js: Combines all reducers using combineReducers from Redux.

Image description

Store

The store holds the state of the application. In the store folder: index.js: Creates the Redux store using the combined reducers.

Image description

Setting Up Redux in App

App.js : Wraps the entire app with the Redux Provider, which makes the Redux store available to any nested components.

Image description

Configuring Redux in the App

components/Counter.js

  • This is a functional component connected to Redux using the connect function from react-redux.

  • mapStateToProps is a function that maps parts of the Redux state to the component's props.

  • mapDispatchToProps is an object that maps action creators to props.

  • connect connects the component to the Redux store, allowing it to access the state and dispatch actions.

Image description

Running the App

Starting the Application

Run npm start to start the React application.

Summary

  1. Actions are dispatched to describe something that happened (like "INCREMENT" or "DECREMENT").
  2. Reducers describe how the application's state changes in response to actions.
  3. Store holds the application's state.
  4. Connecting Components allows them to access the Redux store's state and dispatch actions.

This breakdown covers the foundational parts of a simple Redux setup in a React application. Understanding these sections will help you grasp how Redux manages state and data flow in a React application. If any specific part needs further explanation, feel free to ask!

Top comments (0)