How to Use Redux to Create React App

Read it in 10 Mins

Last updated on
14th Sep, 2022
Published
11th Sep, 2022
Views
9,795
How to Use Redux to Create React App

For JavaScript applications, Redux is a predictable state container. It gets harder to keep the system organized and keep the data flowing as it increases. Redux addresses this issue by using a single global object named Store to manage the state of the application. Redux's core concepts aid in upholding consistency throughout your application, which facilitates testing and debugging. 

More crucially, it offers time-traveling debugging and live code editing. It can easily work with any view layer, including React, Angular, Vue, and others. 

Instead of directly communicating with the store from your UI code when utilizing Redux with any form of UI framework, you need to typically utilise a "UI binding" package to connect Redux with your UI framework. 

Redux and React were created with one another in mind. Redux stores state and updates it in response to actions, but React allows you to express your User Interface as a function of your state. 

The official Redux UI binding library for React is called React Redux. React Redux should be used to bind Redux and React if you want to utilize them both at the same time. 

Redux is intended to centralize your React state data and state logic and make the state management as consistent. 

Core Concept of Redux- 

Single Source of Truth 

The state of your whole application is stored in an object tree within a single store. As whole application state is stored in a single tree, it makes debugging easy, and development faster. 

State is Read-only 

React props are used to pass down the stored data. React does not allow you to directly modify the props object. 

This will aid in maintaining consistency throughout the app. Redux only allows you to update your store data via dispatch functions, for which you must define the action to trigger. 

Changes are Made with Pure Functions 

These functions, which are attached to an action, are also known as reducers. A reducer's job is to take the current state and an action and return the next state. Redux will examine the action request to see if it exists and if it is associated with a reducer.  The reducer function will then be executed to update the store data. 

Setting up of Redux Project  

There are two ways to set up Redux project: 

1.) Install create-React-app. To create a project, use the CLI command create-React-app. 

npm install -g create-React-app 

To start a new project, enter the CLI command (create-React-app) followed by the name of your project (redux-React-demo) and press enter. 

create-React-app redux-React-demo 

2.) You can also use npxthe latest binary that comes with npm v5.2 and higher. Simply add npx before create-React-app (create React app redux toolkitRedux-React demo to start a new project. This initializes create-React-app globally (if it hasn't already been installed) and creates a new project. 

npx create-react-app redux-react-demo 

Now, do the following in your terminal: 

cd redux-react-demo 
npm start 

When Your Application starts just switch to the browser and hit the localhost:3000 and you will see a window as shown below: 

As we can see, create-React-app provides us with a very simple template that includes a text, a link to the React website, and a revolving icon for ReactJS. Create React app Redux typescript is also available in typescript. 

If you are thinking of learning about Reactthen KnowledgeHut with its lowest React js course fees will aid you in achieving the goal.  

Get to know more about React component. 

Project Folder Structure

The following files, with their precise filenames, must exist for your project to be built: 

  • public/index.html is the page template; 
  • src/index.js is the JavaScript entry point. 

To stop or start spinning the React image above, we'll utilize Redux. Following this, let's add the Redux packages listed below: 

npm install --save redux react-redux 

v5.1.1 of React-Redux 

This is utilized so that we can send actions to Redux, which is technically not Redux, but we'll get there, and access and modify its data. 

The documents state: It enables you to send actions to a Redux store for data updates and let your React components read data from one. 

If the command doesn't work for you, try installing the packages individually. You will require the following three things to function with Redux: 

Action Creators: 

The functions that include the action object creation procedure are known as action creators. These operations merely return a standard Js object, an action. It encourages the creation of clean code and aids in achieving reusability. 

Let us know about the action creator that enables users to send the command "ITEMS REQUEST," which asks the server for features of the products items list. The reducer's isLoading state is set to true in the 'ITEMS REQUEST' action type to show the elements are loading even though the server has not yet sent any data. 

The initialState object's isLoading state was false at first since it was assumed that nothing was loading. Whenever data is obtained at the browser, the isLoading state will be provided as false in the associated reducer's 'ITEMS REQUEST SUCCESS' action type. 

const ITEMS_REQUEST = ITEMS_REQUEST ; 
const ITEMS_REQUEST_SUCCESS = ITEMS_REQUEST_SUCCESS ; 
export function itemsRequest(bool,startIndex,endIndex) { 
   let payload = { 
      isLoading: bool, 
      startIndex, 
      endIndex 
   } 
   return { 
      type: ITEMS_REQUEST, 
      payload 
   } 
} 
export function itemsRequestSuccess(bool) { 
   return { 
      type: ITEMS_REQUEST_SUCCESS, 
      isLoading: bool, 
   } 
} 

Utilizing store.dispatch() directly will allow you to dispatch an action. However, it is more likely that you will access it using the connect React-Redux helper method (). Additionally, one can connect numerous action creators well with dispatch function using the bindActionCreators() method. 

The React js course fees KnowledgeHut is offering is the lowest with an in-depth knowledge of the React js . 

Reducers:  

They explain how actions sent to the Redux store affect the application state. 

Make a reducers folder in src and specify reducers for the activities of your app. A reducer example is as follows: 

/* 
 src/reducers/simpleReducer.js 
*/export default (state = {}, action) => { 
 switch (action.type) { 
  case 'SIMPLE_ACTION': 
   return { 
    result: action.payload 
   } 
  default: 
   return state 
 } 
} 

One may merge all of the app's reducers together into unified key reducer by using the combineReducers tool from Redux. The index reducer will be referred to in this application as rootReducer. Create rootReducer.js in your reducers folder and import all reducers specified for your app activities. 

/* 
 src/reducers/rootReducer.js 
*/import combineReducers } from 'redux'; 
import simpleReducer from './simpleReducer';export default combineReducers({ 
 simpleReducer 
}); 

Redux Store:

The Redux store primarily performs the following tasks: 

  • Maintains the application state 
  • The use of getState to access the state. The present state structure of your application is returned by the getState() method. 
  • Permits updating of state by dispatch (action). By "dispatching" an action, the dispatch method causes a state to change. 
  • Registers listeners, A change listener is added via the subscribe(listener). similar to the change listener techniques of Flux. 
  • Using the function returned by subscribe, it manages unregistering listeners (listener). 

Make a store.js file in the src folder and set up the Redux store in it. In the configureStore method, an initialState argument is also definable. 

import createStoreapplyMiddleware } from 'redux'; 
import thunk from 'redux-thunk'; 
import rootReducer from './reducers/rootReducer';export default function configureStore() { 
 return createStore( 
  rootReducer, 
   applyMiddleware(thunk) 
 ); 
} 

Either an object with no keys or an object with initial key values can be the store's defined initialState. Here's an illustration: 

import createStoreapplyMiddleware } from 'redux'; 
import thunk from 'redux-thunk'; 
import rootReducer from './reducers/rootReducer';export default function configureStore(initialState={}) { 
 return createStore( 
   rootReducer, 
   initialState, 
   applyMiddleware(thunk) 
 ); 
} 

Connect React Component to Store 

The connect React binding from React-Redux will be used for this. 

import React, { Component } from 'react'; 
import { connect } from 'react-redux';import logo from './logo.svg'; 
import './App.css';class App extends Component { 
 render() { 
  return ( 
   <div className="App"> 
    <header className="App-header"> 
     <img src={logo} className="App-logo" alt="logo" /> 
     <h1 className="App-title">Welcome to React</h1> 
    </header> 
    <p className="App-intro"> 
     To get started, edit <code>src/App.js</code> and save to reload 
    </p> 
   </div> 
  ); 
 } 
}export default connect()(App); 

mapStateToProps and mapDispatchToProps are the two parameters that connect accepts. These will be covered shortly. Let's import an action now and try it. 

import simpleAction } from './actions/simpleAction'; 

The connect parameter's mapStateToProps option enables the Redux component's React component to subscribe to state updates. 

const mapStateToProps = state => ({ 
 ...state 
}) 

Connect's mapDispatchToProps parameter has two possible values: 

  • an object of action creators wrapped into a dispatch. 
  • a dispatch parametered function. The function should return an object that binds action creators using dispatch. As an alternative, you can utilize the Redux helper function bindActionCreators(). 
const mapDispatchToProps = dispatch => ({ 
simpleAction: () => dispatch(simpleAction()) 
})

The component's props are combined when mapStateToProps and mapDispatchToProps are supplied as connect options. 

export default connect(mapStateToPropsmapDispatchToProps)(App); 

  • Let's check to see if the store is linked and operating as expected right now. Add a button to app.js 

<button>Test redux action</button> 

  • Make a function that gets invoked whenever the button is pressed. 

simpleAction = (event) => { 
this.props.simpleAction(); 
} 
Bind a function to the onClick event of a button. 
<button onClick={this.simpleAction}>Test redux action</button> 
To view changes in component props, add a pre tag. 
<pre> 
{ 
JSON.stringify(this.props) 
} 
</pre> 

Conclusion 

Using CRA is fantastic when you need to start your project sooner. However, it is advisable to start your React project from scratch if you want some control over your webpack configuration. 

Redux has a lot of boilerplates and moving components, but once you get the hang of it, it just makes more sense in terms of how this state management technology aids in managing big projects.  

Don't use Redux just because someone says you should - spend some time to explore the potential benefits and cons of utilizing it. 

Some pointers as to why you should consider using Redux: 

  • You have a good deal of data that changes over time. 
  • For your state, you require a single source of truth. 
  • You discover that it is no longer adequate to retain all of your states in a top-level component. 

We hope this article inculcates interest in you for web development. You can start your career in web development with the best web development training institute. 

Frequently Asked Questions (FAQs)  

1. Does create-React-app Use Redux?  

No, create-React-app does not use Redux. You have to install it manually. 

2. How do I add Redux to React app? 

The recommended way to start new apps with React and Redux is by using the official create React app Redux template or Redux+TS template forcreate React App with Redux, which takes advantage of Redux Toolkit and React Redux's integration with React components. 

npx create-react-app my-app --template redux 

3. How do I create my own React app?   

There are two ways to set up your project: 

1.) Install create-React-app. To create a project, use the CLI command create-React-app. 

npm install -g create-react-app 

To start a new project, enter the CLI command (create-React-app) followed by the name of your project (Redux-React-demo) and press enter. 

create-react-app redux-react-demo 

2.) You can also use npx, which is a latest binary that comes with npm v5.2 and higher. Simply add npx before create-react-app redux-react-demo to start a new project. This initializes create React app Redux globally (if it hasn't already been installed) and creates a new project. 

npx create-react-app redux-react-demo 

4. What is Redux in React JS?   

Redux is intended to centralize your React state data and state logic and make the state management consistent. 

5. Is Redux hard to learn? 

Not at all, in smaller projects, you might not recognize Redux's strength, but as your app gets bigger, you'll start to realize how simple managing the state isthanks to Redux. Therefore, practice as much as you can, and Redux won't be as challenging as it seems.  

6. Is Redux frontend or backend?

Redux can be used for the client side (frontend) with user interfaces, as should be obvious. Redux can be utilized on the server side, though it is only JavaScript. 

Profile

Ishan Jain

Blog Author

I am a Full Stack developer from Jaipur. I also work as a Javascript Tutor in my free time. Along with project development, I also write tech blogs.