How to Setup Redux and Connect to React App

Ishwar Deoolkar
Nerd For Tech
Published in
13 min readMay 13, 2021

--

Here I am sharing my knowledge and experience about how we can set up Redux and Connect to React App (Everything you need to know).

React-Redux

With these rapidly changing of world. We can’t sit idle, We need to move on and We need give our best in every ups and downs. How we can give our best ? Answer is learning day by day. If you have a 6 years of experience or fresher, you need to learn everyday to get better version of yourself.

Before moving forward, We will try to understand what is the definition of redux and all are the benefits of the same.

Introduction

Redux is a predictable state container for JavaScript apps. To understand what it means let’s break it down into three parts.

  • It is for javascript apps
  • It is a state container
  • It is predictable

Let’s talk about each of these -

Redux is for javascript applications.

  • Redux is not tied to react.
  • It can be used with any framework such as React, Vue, and Angular or event with vanilla javascript.
  • So redux is a library for javascript applications.

Redux is a state container

  • Redux is used to store the state for your applications.
  • So what does that mean, Let’s consider a react app as a state of components?
  • The state of an app is the state represented by all the individual components of that application. So this includes data and UI logic. Refer to the image below.
Component state by Ishwar Deoolkar
  • If your application is medium to large in size. So the state of the application would look like this. Refer to the image below.
Application Component state by Ishwar Deoolkar
  • Redux will store and manage the application state.

Redux is a predictable

  • Predictable in what way? So let’s refer to the previous point. (read above Redux is a state container).
  • The state of an application can change. For example — todo list app — item(pending) → item(completed).
  • In redux, all state transitions are explicit and it is possible to keep track of them and the changes to your application state become predictable.

React-Redux

Before we talk about React-Redux, I will assume that you know the fundamentals of reacts, Such as What is react, How do we create components, How we manage the state and props in components, and so on. As I have explained what is redux in the above section.

Let’s talk about React+Redux,

  • Why would we want to use redux in react applications?
  • Components in React have their own state.
  • Why do we need another tool to help manage that state?

So let me help you that to understand those questions. Consider a react application may consist of several components nested at various levels. Refer to the image below.

Application With Nested Component by Ishwar Deoolkar

Where component C is the parent of A and B. In this case, If there is some Data only in component A but, component B also wants that data. We know Component B cannot access the data because a component can talk only to its parent or child (Not cousins). So how we can do that? Answer to question using lifting props.

Lifting the state from one component to another component by Ishwar Deoolkar

Let’s talk a few seconds about lifting the props or lifting the state.

Lifting the state

As we know, every component in React has its own state. Because of this sometimes data can be redundant and inconsistent. So, by Lifting the state we make the state of the parent component as a single source of truth and pass the data of the parent in its children.

Time to use Lift the State: If the data in “parent and children components” or in “cousin components” is Not in Sync. This all about lifting state. Want to learn more about lifting state visit this link.

When your application grows then it very difficult to maintain the state. And it’s very difficult to lift the state from one component to another component. So then redux comes into play a big role in maintaining your application state.

In redux, we need to create a store where all our application states are sitting. From the store, you can directly pass the state to any component. So with this no need to do state lifting and all. Check the image below for how it looks.

Redux store by Ishwar Deoolkar

So that it’s about redux and react-redux. Let’s move on to how to set up Redux and connect to React App.

How to setup Redux

Install the redux from the npm package or run this command in your terminal. Once you install redux. it will be added to the package.json file.

// Install with npm
npm install redux
or // Install with yarn
yarn install redux
or // Install with bower
bower install redux

Let me explain taking one real-world scenario, Suppose you have a store and in your store have multiple things are available such as Cakes, IceCreams, so on. In the shop, We have caked stored on the shelf and we have a hire shopkeeper to maintain the caked shelf. Suppose a customer comes to your store and asks the shopkeeper I want to buy cakes.

Then the shopkeeper asks the customer how many quantities of cakes they want to buy. Customer reply to the shopkeeper wants to buy 10 cakes. And the Shopkeeper's job is to keep track of how many quantities of cakes are available in the store. For example — 100 cakes are available.

Let’s recap the requirements of customers and other details.

  • The customer wants to buy cake 10 cakes. — (Action — BUY_CAKE)
  • Shopkeeper keeps track of cakes of quantities available in the store — 100 cakes (Store — ‘Cakes’).

Redux has three steeps — Actions, Reducers, and Store. Refer to the image below.

Redux flow by Ishwar Deoolkar

Let’s see how the folder structure look like

Redux-Folder-Structure by Ishwar Deoolkar

In the above image, you able to see the folder structure of multiple apps — such as Cake, iceCream, and sweetMart.

Here some brief about each of them —

Actions

  • Actions are the only source of information for the store.
  • It carries a payload of information from your application to store.
  • Actions are plain JavaScript object that must have a type attribute to indicate the type of action performed. It tells us what had happened. Types should be defined as string constants in your application as given below
cakesTypes.jsexport const BUY_CAKE = 'BUY_CAKE';
iceCreamTypes.jsexport const BUY_ICECREAM = "BUY_ICECREAM";
sweetMartTypes.jsexport const BUY_KUNDA = "BUY_KUNDA";
export const BUY_KAJUKATLI = "BUY_KAJUKATLI";
  • Apart from this type of attribute, the structure of an action object is totally up to the developer. It is recommended to keep your action object as light as possible and pass only the necessary information.
  • To cause any change in the store, you need to dispatch an action first by using the store.dispatch() function. The action object is as follows −
cakesAction.js{ type: BUY_CAKE, info: "Buy cake is redux action" }
{ type: BUY_CAKE, payload: number }
iceCreamActions.js{ type: BUY_ICECREAM, info: "Buy ice cream is redux action" }
{ type: BUY_ICECREAM, payload: number }
sweetMartActions.js{ type: BUY_KUNDA, info: "Buy ice cream is redux action" }
{ type: BUY_KAJUKATLI, payload: number }
  • Action creators are the functions that encapsulate the process of creation of an action object.
cakesActions.js// Import types of cakes.
import { BUY_CAKE } from './cakesTypes.js';
export const buyCake = () => {
return {
type: BUY_CAKE,
info: "Buy cake is redux action"
}
}
iceCreamActions.js// Import types of icecream.
import { BUY_ICECREAM } from './iceCreamActions.js';
export const buyIceCream = (number = 1) => {
return {
type: BUY_ICECREAM,
info: "Buy ice cream is redux action",
payload: number
}
}
sweetMartActions.js// Import types of sweetmart.
import { BUY_KUNDA, BUY_KAJUKATLI } from './sweetMartActions.js';
export const buyKunda = () => {
return {
type: BUY_KUNDA,
info: "Buy kunda is redux action"
}
}
export const buyKajuKatli = (number = 1) => {
return {
type: BUY_KAJUKATLI,
info: "Buy kunda is redux action"
payload: number
}
}

Reducers

  • Reducers are a pure function in Redux.
  • Pure functions are predictable.
  • Reducers are the only way to change states in Redux. It is the only place where you can write logic and calculations.
  • The reducer function will accept the previous state of the app and action being dispatched, calculate the next state, and returns the new object.
  • The following few things should never be performed inside the reducer −
    1. Mutation of functions arguments
    2. API calls & routing logic
    3. Calling non-pure function e.g. Math.random()
  • The following is the syntax of a reducer −
(state,action) => newState
  • Let us continue the example of showing the cakes available on a web page. Discussed in the action creators module. Let us see below how to write its reducer.
cakesReducer.js// Import types. 
import { BUY_CAKE } from './cakesTypes.js';
const cakeInitialState = {
numberOfCakes: 100
}
const cakeReducer = (state = cakeInitialState, action) => {
switch(action.type){
case BUY_CAKE:
return {
...state,
numberOfCakes: state.numberOfCakes - 1
}
default:
return state;
}
}
export default cakeReducer;
iceCreamReducer.js// Import types of icecream.
import { BUY_ICECREAM } from './iceCreamActions.js';
const iceCreamInitialState = {
numberOfIceCreams: 20
}
const iceCreamReducer = (state = iceCreamInitialState, action) => {
switch(action.type){
case BUY_ICECREAM:
return {
...state,
numberOfIceCreams: state.numberOfIceCreams - action.payload
}
default:
return state;
}
}
export default iceCreamReducer;
sweetMartReducer.js// Import types of sweetmart.
import { BUY_KUNDA, BUY_KAJUKATLI } from './sweetMartActions.js';
const sweetMartInitialState = {
numberOfKunda: 200,
numberOfKajuKatli: 100
}
const sweetMartReducer = (state = sweetMartInitialState, action) => {
switch(action.type){
case BUY_KUNDA:
return {
...state,
numberOfKunda: state.numberOfKunda - 1
}
case BUY_KAJUKATLI:
return {
...state,
numberOfKajuKatli: state.numberOfKajuKatli - action.payload
}
default:
return state;
}
}
export default sweetMartReducer;

Store

  • A store is an immutable object tree in Redux.
  • A store is a state container that holds the application’s state.
  • Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer.
  • Let us see how we can create a store using the createStore method from Redux. One need to import the createStore package from the Redux library that supports the store creation process as shown below −
store.js import { createStore } from 'redux';// Import cake reducer from cakeApp.
import cakeReducer from '../cakes/cakesReducer';
const store = createStore(cakeReducer);

The above snippets show how we can create a store and how the reducer is pass to the store. this shows to call a single reducer to store. But suppose you have multiple apps such as Cake, IceCream, and SweetMart.

And each app has its individual reducers so how do we call all these reducers to a single store. In redux, we need to declare only one store and that store contains multiple apps. But we can’t declare multiple stores in redux. So without spoiling redux store terminology how we can achieve this — using combineReducers from the redux. Let me write code and show you how to combine multiple reducers in one place.

rootReducers.jsimport { combineReducers } from 'redux';// Import cake reducer from CakeApp.
import cakeReducer from '../cakes/cakesReducer';
// Import icecream reducer from IceCreamApp.
import iceCreamReducer from '../iceCream/iceCreamReducer';
// Import sweetmart reducer from SweetMartApp.
import sweetMartReducer from '../sweetMart/sweetMartReducer';
// Combine the each reducers using combineReducers.
const rootReducers = combineReducers({
cake: cakeReducer,
iceCream: iceCreamReducer,
sweetMart: sweetMartReducer
});
export default rootReducers;

Now you can import these rootReducers in your store.

store.jsimport { createStore } from 'redux';// Import rootReducers from all redcuers apps.
import rootReducers from './rootReducers';
const store = createStore(rootReducers);

Let’s import all your actions into one file-

index.jsexport { buyCake } from './cake/cakeActions';
export { buyIceCream } from './iceCream/iceCreamActions';
export { buyKunda, buyKajuKatli } from './sweetMart/sweetMartActions';

Redux itself is synchronous, so how the async operations like network requests work with Redux?

Middleware

  • Redux middleware function provides a medium to interact with dispatched action before they reach the reducer.
  • Customized middleware functions can be created by writing high-order functions (a function that returns another function), which wraps around some logic.
  • Multiple middlewares can be combined to add new functionality, and each middleware requires no knowledge of what came before and after. You can imagine middlewares somewhere between action dispatched and reducer.
  • Commonly, middleware is used to deal with asynchronous actions in your app.
  • Redux provides with API called applyMiddleware which allows us to use custom middleware as well as Redux middlewares like redux-thunk and redux-promise, redux-logger, redux-saga. It applies middlewares to store. The syntax of using applyMiddleware API is −
applyMiddleware(...middleware)
  • There are multiple middlewares you can pick anyone from the list. So I will be using redux-logger. Let’s install redux-logger using the npm command.
// Install with npm
npm install redux-logger
or// Install with yarn
yarn install redux-logger

Once you have installed the middleware and it will get added to the package.json file. And this can be applied to store as follows −

store.jsimport { createStore, applyMiddleware } from 'redux';// Import logger from redux logger package.
import logger from 'redux-logger';
// Import rootReducers from all redcuers apps.
import rootReducers from './rootReducers';
const store = createStore(rootReducers, applyMiddleware(logger));export default store;

You want to know more about middleware. Check this link and Refer to the image below to get how middleware works.

Redux-Middleware-Flow by Ishwar Deoolkar

Now you have set up the redux, Let’s talk about how you can connect your redux to your react app. So before writing some code we need to install react-redux. To install react-redux run this command in your terminal.

// Install with npm
npm install react-redux
or// Install with yarn
yarn install react-redux

In your react app there is a file called App.js. Import the redux store which you have set up and import provider from react-redux.

Redux provides the react-redux package to bind react components with two utilities as given below −

  • Provider — Provider makes the store available to the rest of the application.
  • Connect — Connect function helps react component to connect to the store, responding to each change occurring in the store’s state.

Suppose your app.js look like this.

App.jsimport React from 'react';
import { Provider } from 'react-redux';
import store from './redux/store';
import CakeContainer from '../components/CakeContainer/CakeContainer';
const App = () => {
return (
<Provider store={store}>
<div className="app-container">
<CakeContainer />
</div>
</Provider>
)
}
export default App;

Whenever a change occurs in a react-redux app, mapStateToProps() is called. In this function, we exactly specify which state we need to provide to our react component. With the help of connect() function explained below, we are connecting these app’s states to react component. Connect() is a high-order function that takes a component as a parameter. It performs certain operations and returns a new component with correct data which we finally exported. With the help of mapStateToProps(), we provide these store states as a prop to our react component. This code can be wrapped in a container component.

CakesContainer.jsconst mapStateToProps = state => {
return {
numOfCakes: state.cake?.numOfCakes
}
}

mapDispatchToProps() function receives dispatch function as a parameter and returns your callback props as a plain object that you pass to your react component. mapDispatchToProps() is used to dispatch an action to store. In react-redux, components cannot access the store directly. The only way is to use connect()

CakeContainer.jsconst mapDispatchToProps = dispatch => {
return {
buyCake: () => dispatch(buyCake())
}
}

Let us understand how the react-redux works through the below diagram −

React-Redux-Work by Ishwar Deoolkar

STORE − Stores all your application state as a JavaScript object

PROVIDER − Makes stores available

CONTAINER − Get apps state & provide it as a prop to components

COMPONENT − User interacts through view component

ACTIONS − Causes a change in store, it may or may not change the state of your app

REDUCER − Only way to change app state, accept state and action and return updated state.

Redux is an independent library and can be used with any UI layer. React-redux is the official Redux, UI binding with the react. Moreover, it encourages a good react Redux app structure. React-redux internally implements performance optimization, so that component re-render occurs only when it is needed.

To sum up, Redux is not designed to write the shortest and the fastest code. It is intended to provide a predictable state management container. It helps us understand when a certain state changed, or where the data came from.

CakeContainer.jsimport React from 'react';
import { connect } from 'react-redux';
import { buyCake } from '../redux/index';
const CakeContainer = (props) => {
return (
<div className="cake-container">
<h1>Without Hooks - Cake App</h1>
<h2>Number of cakes - {props.numOfCakes}</h2>
<button type="button" onClick={props.buyCake}>Buy cake</button>
</div>
)
}
const mapStateToProps = state => {
return {
numOfCakes: state.cake?.numOfCakes
}
}
const mapDispatchToProps = dispatch => {
return {
buyCake: () => dispatch(buyCake())
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(CakeContainer);

Conclusion

That end’s how we can set up redux and connect to the react app. Give it a try to set up the redux with your react app.

Let me know this article helpful for you and Are there any certain features does one thinks I missed or should be covered? Let me know within the comments below!

Happy coding…!!!

--

--

Ishwar Deoolkar
Nerd For Tech

Frontend Developer @Jeeves || jQuery || ReactJs Developer || VueJs Developer || Angular Developer || Software Engineer || GraphQL || Redux and Recoil || VueX