Create Your First App in React with Redux | Counter app

Author: neptune | 30th-Mar-2023
#React.js

Creating your first app in React can be a daunting task, but with the right guidance, it can be a fun and rewarding experience. In this article, we will guide you through the process of creating your first app in React, including reducers, actions, and state. We will provide a step-by-step explanation of each process, along with headings to help you navigate through the article.


Step 1: Setting up the Environment

Before we start creating our app, we need to set up our environment. We will be using Node.js and npm to install the necessary packages. Here are the steps to set up your environment:


1. Install Node.js from the official website.


2. Open your terminal or command prompt and type the following command to check if Node.js is installed:


  >>> node -v

This command will display the version of Node.js installed on your system.


3. Next, we need to install npm. Type the following command in your terminal:


>>>   npm install npm@latest -g

This command will install the latest version of npm globally on your system.



4. Once npm is installed, we can create our React app. Type the following command in your terminal:


>>>   npx create-react-app my-app

This command will create a new React app named "my-app" in your current directory.


Step 2: Understanding Reducers

Reducers are functions that take the current state and an action as arguments and return a new state. They are used to update the state of our app based on the actions performed by the user. 

Here's how we can create a reducer:

1. Create a new file named "reducer.js" in the "src" folder of your React app.


2. In the "reducer.js" file, define a function named "reducer" that takes two arguments: "state" and "action".


3. Inside the "reducer" function, use a switch statement to handle different types of actions. 


In src/reducer.js file :


 const initialState = {

    count: 0

 };


 const reducer = (state = initialState, action) => {

    switch (action.type) {

        case 'INCREMENT':

            return { count: state.count + 1 };

        case 'DECREMENT':

            return { count: state.count - 1 };

        default:

            return state;

    }

 };


 export default reducer;


In the above file, we are handling two types of actions: "INCREMENT" and "DECREMENT". If the action type is "INCREMENT", we return a new state object with the count incremented by 1. 

If the action type is "DECREMENT", we return a new state object with the count decremented by 1. 

If the action type is not recognized, we simply return the current state.


Step 3: Creating Actions

Actions are objects that describe what happened in our app. They are used to trigger the reducers and update the state of our app. 

Here's how we can create an action:

1. Create a new file named "actions.js" in the "src" folder of your React app.


2. In the "actions.js" file, define a function named "increment" that returns an object with a "type" property set to "INCREMENT". 

In actions.js file:


 export const increment = () => {


    return {

        type: 'INCREMENT'

    };


 };

In the above file, we are defining an action named "increment" that has a type of "INCREMENT". This action will be used to increment the count in our app.


3. Similarly, define a function named "decrement" that returns an object with a "type" property set to "DECREMENT". 

In actions.js file:


 export const decrement = () => {


    return {

        type: 'DECREMENT'

    };

 };


In the same  actions.js file, we are defining an action named "decrement" that has a type of "DECREMENT". This action will be used to decrement the count in our app.


Complete src/actions.js file:


 export const increment = () => {


    return {

        type: 'INCREMENT'

    };


 };


 export const decrement = () => {


    return {

        type: 'DECREMENT'

    };

 };


Step 4: Creating Reducer to update state

1. Open the "reducer.js" file in the "src" folder of your React app.


2. Define reducer for count . 

In src/reducers.js file:



 const initialState = {

    count: 0

 };


 const reducer = (state = initialState, action) => {

    switch (action.type) {

        case 'INCREMENT':

            return { count: state.count + 1 };

        case 'DECREMENT':

            return { count: state.count - 1 };

        default:

            return state;

    }

 };


 export default reducer;


In the above file, we are defining a reducer for count. The count reducer handles "INCREMENT" and "DECREMENT" actions.


Step 5: Managing State

State is an object that represents the current state of our app. It is used to render the UI and update the app based on user actions. 

Here's how we can manage state in our app:


1. Open the "App.js" file in the "src" folder of your React app.


2. Redux is a state management library that allows you to manage global state in your application. 

3. Redux uses a single store to hold the state of the entire application and provides a set of methods to manipulate the state. 

4. You can dispatch actions to update the state, and use reducers to handle those actions and update the state accordingly.

5. Import the "increment" and "decrement" actions from the "actions.js" file.



6. Add an "onClick" event to the increment button that dispatches the "increment" action. 

In src/App.js file:

 import { increment, decrement } from './actions';


 function App(props) {

  return (

    <div>    

      <h3>Count: {props.count}</h3>

      <button onClick={props.increment}>Increment</button>

      <button onClick={props.decrement}>Decrement</button>

    </div>

  );

 }


Step 6: Connecting Components to Redux

To connect our components to Redux, we need to use the "connect" function from the "react-redux" package. Here's how we can connect our components to Redux:


1. Open the component file that you want to connect to Redux.


2. Import the "connect" function from the "react-redux" package.


3. Define a function named "mapStateToProps" that takes the state as an argument and returns an object with the props that you want to pass to the component. 

For example:


 const mapStateToProps = (state) => {

  return {

    count: state.count

  };

 };



In this example, we are defining a mapStateToProps function that returns an object with the count props from the state.


4. Define a function named "mapDispatchToProps" that takes the dispatch function as an argument and returns an object with the actions that you want to dispatch. 

For example:


 const mapDispatchToProps = (dispatch) => {

  return {

    increment: () => dispatch(increment()),

    decrement: () => dispatch(decrement())

  };

 };


In this example, we are defining a mapDispatchToProps function that returns an object with the increment and decrement actions.


5. Use the "connect" function to connect the component to Redux. 

For example:



 export default connect(mapStateToProps, mapDispatchToProps)(App);




In this example, we are connecting the APP to Redux using the mapStateToProps and mapDispatchToProps functions.


Complete src/App.js file:


 import React from 'react';

 import { connect } from 'react-redux';

 import { increment, decrement } from './actions';


 function App(props) {

  return (

        <div>

          <h3>Count: {props.count}</h3>

          <button onClick={props.increment}>Increment</button>

          <button onClick={props.decrement}>Decrement</button>

        </div>

  );

}


const mapStateToProps = (state) => {

  return {

    count: state.count

  };

};


const mapDispatchToProps = (dispatch) => {

  return {

    increment: () => dispatch(increment()),

    decrement: () => dispatch(decrement())

  };

};


export default connect(mapStateToProps, mapDispatchToProps)(App);



  

In the above file, we are using createStore to create a Redux store with an initial state and a reducer function. We are then using connect to connect our Counter component to the store and passing in the mapStateToProps and mapDispatchToProps functions. 


Finally, we are rendering the App component inside a Provider component that provides the store to all connected components.


Conclusion

Congratulations! You have successfully created your first app in React with Redux. You can now create more complex apps with multiple components and state management using Redux. Keep practising and exploring the possibilities of React and Redux to become a proficient developer.

This article provides a step-by-step guide on how to create your first app in React with Redux, including setting up the environment, understanding reducers, creating actions, managing state, and connecting components to Redux.





anonymous | March 30, 2023, 6:09 p.m.

Amazing 👍



Related Blogs
React: Slideshow App | Fresco Play Hackerrank
Author: neptune | 05th-Nov-2023
#React.js
One interesting project that showcases these qualities is the Slideshow App, a simple yet impactful application that allows users to navigate through a collection of slides...

React.js vs React Native – What's the Difference?
Author: neptune | 26th-Mar-2023
#React.js
React.js and React Native are both frameworks developed by Facebook for building user interfaces. However, they are not the same and have different use cases...

Essential Topics to Master React JS
Author: neptune | 21st-Feb-2024
#React.js
A Comprehensive Guide to Components, State, JSX, Event Handling, Routing, Redux, Hooks, Testing, Performance Optimization, and Server-Side Rendering...

Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Opportunities - React Django Developer
Author: neptune | 14th-Apr-2023
#React.js #Django
React Django stack is popular for building web applications. Opportunities for React Django developers in Full Stack, Web, and Software development roles...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

Why React Refuses to Die ?
Author: neptune | 01st-Jun-2023
#React.js
React's success stems from addressing UI development challenges, nurturing a vibrant ecosystem, and its demand in the job market. Challenges exist, but React continues to evolve and remain relevant...

😱 How React Kicks Off OOPs ? 😱
Author: neptune | 01st-Jun-2023
#React.js
React kicks off OOPs by replacing inheritance with composition, achieving code reuse and modularity while promoting functional programming...

All You Need to Know About Pure Functions & Impure Functions in JavaScript
Author: neptune | 02nd-Apr-2023
#JavaScript #React.js
You should try to use pure functions whenever possible and avoid using impure functions unless necessary...

Components and Props: Understanding the Backbone of React Applications
Author: neptune | 23rd-Jul-2023
#React.js
React is a popular JavaScript library for building user interfaces. One of the fundamental concepts in React is the use of components and props...

Functional vs Class Components in React: All you need to know?
Author: neptune | 21st-Apr-2023
#React.js
React components are building blocks for UIs. They can be functional (stateless) or class (stateful). Components are called using their names as HTML tags...

Celebrating 10 Years of React: A Decade of Innovation
Author: neptune | 01st-Jun-2023
#React.js
React celebrates its 10th anniversary, revolutionizing frontend development with its innovative concepts, ecosystem growth, and impact on mobile development...

State in React: Component State and Controlling Behavior
Author: neptune | 21st-Feb-2024
#JavaScript #React.js
React, a popular JavaScript library for building user interfaces, introduces the concept of state and lifecycle methods to help developers manage the dynamic nature of components...

Decode Secret Language of React: Game-Changer for Web Developers
Author: neptune | 25th-Feb-2024
#JavaScript #React.js
JSX is a syntax extension for JavaScript recommended by React for describing what the UI should look like...

View More