DeveloperBreeze

Introduction

In this tutorial, we will learn how to build a modern web application using React and Redux. React is a popular JavaScript library for building user interfaces, while Redux is a predictable state container that helps manage application state. We'll cover the basics of setting up a React project, integrating Redux, and implementing a simple application to demonstrate these tools.

Prerequisites

Before starting this tutorial, you should have a basic understanding of JavaScript and familiarity with the command line. Additionally, ensure you have Node.js and npm (Node Package Manager) installed on your machine.

Step 1: Setting Up Your React Application

First, we need to set up a new React application. We'll use Create React App, a popular toolchain for setting up React projects with no build configuration.

  1. Create a New React App

Open your terminal and run the following command to create a new React application:

   npx create-react-app my-react-app

This command will create a new directory called my-react-app with all the necessary files and dependencies.

  1. Navigate to Your Project Directory
   cd my-react-app
  1. Start the Development Server
   npm start

This command starts the development server and opens your new React application in the browser.

Step 2: Installing Redux and React-Redux

To manage our application's state with Redux, we need to install Redux and the React-Redux bindings.

  1. Install Redux and React-Redux

Run the following command in your project directory:

   npm install redux react-redux

Step 3: Setting Up Redux

Now, let's set up Redux in our React application.

  1. Create a Redux Store

In the src directory, create a new file called store.js and add the following code:

   import { createStore } from 'redux';

   const initialState = {
     count: 0,
   };

   const reducer = (state = initialState, action) => {
     switch (action.type) {
       case 'INCREMENT':
         return { ...state, count: state.count + 1 };
       case 'DECREMENT':
         return { ...state, count: state.count - 1 };
       default:
         return state;
     }
   };

   const store = createStore(reducer);

   export default store;

This code sets up a simple Redux store with an initial state containing a count property and a reducer function to handle INCREMENT and DECREMENT actions.

  1. Provide the Redux Store to Your React Application

In the src/index.js file, wrap your <App /> component with the <Provider> component from react-redux, passing it the store as a prop.

   import React from 'react';
   import ReactDOM from 'react-dom/client';
   import { Provider } from 'react-redux';
   import store from './store';
   import App from './App';
   import './index.css';

   const root = ReactDOM.createRoot(document.getElementById('root'));
   root.render(
     <Provider store={store}>
       <App />
     </Provider>
   );

Step 4: Connecting React Components to Redux

Let's connect our React components to the Redux store to interact with the application state.

  1. Create a Counter Component

In the src directory, create a new file called Counter.js and add the following code:

   import React from 'react';
   import { useSelector, useDispatch } from 'react-redux';

   const Counter = () => {
     const count = useSelector((state) => state.count);
     const dispatch = useDispatch();

     const increment = () => {
       dispatch({ type: 'INCREMENT' });
     };

     const decrement = () => {
       dispatch({ type: 'DECREMENT' });
     };

     return (
       <div>
         <h1>Counter: {count}</h1>
         <button onClick={increment}>Increment</button>
         <button onClick={decrement}>Decrement</button>
       </div>
     );
   };

   export default Counter;

This code defines a Counter component that uses the useSelector hook to access the count state and the useDispatch hook to dispatch actions.

  1. Use the Counter Component in Your App

Open the src/App.js file and add the Counter component:

   import React from 'react';
   import Counter from './Counter';

   const App = () => {
     return (
       <div className="App">
         <h1>React and Redux Counter</h1>
         <Counter />
       </div>
     );
   };

   export default App;

Conclusion

Congratulations! You have successfully set up a React application with Redux for state management. You created a simple counter application to demonstrate the integration of Redux in a React project. From here, you can explore more advanced concepts like middleware, asynchronous actions, and integrating APIs to build more complex applications.

Next Steps

  • Learn about Redux middleware like Redux Thunk for handling asynchronous actions.
  • Explore React Router for adding navigation to your application.
  • Integrate APIs to fetch and manage data in your application.

Continue Reading

Discover more amazing content handpicked just for you

Article

Mastering Modern Web Development: Trends, Tools, and Tutorials for 2025 and Beyond

  • Core Functionality: Develop a simple blog that fetches posts from an external API.
  • Enhancements: Integrate a micro frontend component (e.g., a comment widget) developed with React.
  • AI Integration: Add a recommendation engine using a third-party machine learning API to suggest related posts.
  • Containerize Your App: Create a Dockerfile and build your image.
  • Deploy with Kubernetes: Use a simple Kubernetes setup to manage your container, ensuring scalability and high availability.

Feb 11, 2025
Read More
Article

Integrating Flowbite with Tailwind CSS: A Step-by-Step Tutorial

This command generates a package.json file with default configurations, which will manage your project's dependencies.

Tailwind CSS is a utility-first CSS framework that allows for rapid UI development. Follow these steps to install and configure Tailwind CSS in your project.

Oct 24, 2024
Read More
Tutorial
javascript

Automatically Detect New Components in Storybook Without Restarting the Server

npm run storybook:watch

This enables Storybook to automatically detect new components, saving you time by not having to restart the server after every file addition.

Oct 10, 2024
Read More
Tutorial
javascript

التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها

التعامل مع JSON هو جزء أساسي من تطوير تطبيقات الويب الحديثة. سواء كنت تحتاج إلى جلب البيانات من API أو كتابة بيانات إلى خادم، فإن فهم كيفية قراءة وكتابة JSON سيساعدك في بناء تطبيقات قوية وقابلة للتوسيع.

من خلال هذا الدليل، تعلمنا كيفية تحويل الكائنات إلى JSON باستخدام JSON.stringify()، وكيفية قراءة بيانات JSON باستخدام JSON.parse()، وكذلك كيفية جلب البيانات من API والتعامل مع JSON المعقد.

Sep 26, 2024
Read More
Tutorial
javascript

Understanding Closures in JavaScript: A Comprehensive Guide

Closures are commonly used to create private variables, which are not accessible from outside the function:

function counter() {
    let count = 0;

    return function() {
        count++;
        console.log(count);
    };
}

const increment = counter();
increment();  // Output: 1
increment();  // Output: 2
increment();  // Output: 3

Aug 30, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

No preview available for this content.

Aug 21, 2024
Read More
Cheatsheet
javascript css +1

Building a Chrome Extension: A Step-by-Step Tutorial

{
  "manifest_version": 3,
  "name": "My Chrome Extension",
  "version": "1.0",
  "description": "A simple Chrome extension example.",
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/icon16.png",
      "48": "images/icon48.png",
      "128": "images/icon128.png"
    }
  },
  "permissions": [
    "activeTab"
  ]
}
  • manifest_version: Specifies the version of the manifest file format. Version 3 is the latest and recommended version.
  • name: The name of your extension as it will appear in the Chrome Web Store and in the extension list.
  • version: The version of your extension, which must be updated with each new release.
  • description: A short description of what your extension does.
  • action: Defines the behavior of your extension's toolbar button, including the popup that will be displayed when clicked.
  • permissions: Specifies the permissions your extension needs to function. Here, activeTab allows the extension to interact with the current tab.

Aug 20, 2024
Read More
Cheatsheet
javascript

React Performance Optimization Cheatsheet: Hooks, Memoization, and Lazy Loading

For very large lists, consider using windowing libraries like react-window to only render a subset of the list items that are currently visible.

import React from 'react';
import { FixedSizeList as List } from 'react-window';

const Row = ({ index, style }) => (
  <div style={style}>Row {index}</div>
);

function MyList({ itemCount }) {
  return (
    <List
      height={400}
      itemCount={itemCount}
      itemSize={35}
      width={300}
    >
      {Row}
    </List>
  );
}

export default MyList;

Aug 20, 2024
Read More
Tutorial
javascript

Creating a Personal Dashboard with React and APIs: Keep Your Dev Life Organized

Add this component to your dashboard:

import TodoList from './TodoList';

...

<div className="widget">
  <h3>To-Do List</h3>
  <TodoList />
</div>

Aug 20, 2024
Read More
Tutorial
javascript nodejs

Building a React Application with Vite and Tailwind CSS

  • React Router: For handling client-side routing.
  npm install react-router-dom

Aug 14, 2024
Read More
Tutorial
javascript php

Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

In vite.config.js, set up Vite to work with React:

   import { defineConfig } from 'vite';
   import laravel from 'laravel-vite-plugin';
   import react from '@vitejs/plugin-react';

   export default defineConfig({
       plugins: [
           laravel({
               input: ['resources/css/app.css', 'resources/js/app.jsx'],
               refresh: true,
           }),
           react(),
       ],
   });

Aug 14, 2024
Read More
Tutorial
javascript

Integrating Vite with React in a Laravel Project: A Comprehensive Guide

This method helps manage configuration settings across different environments.

Integrating React with Laravel using Vite provides a powerful and efficient way to build modern web applications. With Vite’s fast development server, hot module replacement, and optimized production builds, you can create dynamic, high-performance React components that seamlessly integrate with Laravel’s backend.

Aug 14, 2024
Read More
Tutorial

Integrating Vite with Laravel for Modern Web Development

Install the necessary npm dependencies:

   npm install

Aug 14, 2024
Read More
Tutorial

Getting Started with Vite: A Fast Frontend Build Tool

   npm install

Or with Yarn:

Aug 14, 2024
Read More
Tutorial
dart

Building an Advanced Weather App with Flutter and Dart

Create a new file lib/services/weather_service.dart to handle API requests:

import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/weather.dart';

class WeatherService {
  final String apiKey = 'YOUR_API_KEY';
  final String baseUrl = 'https://api.openweathermap.org/data/2.5/weather';

  Future<Weather> fetchWeather(String city) async {
    final response = await http.get(Uri.parse('$baseUrl?q=$city&appid=$apiKey&units=metric'));

    if (response.statusCode == 200) {
      return Weather.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load weather data');
    }
  }
}

Aug 12, 2024
Read More
Tutorial
dart

Introduction to Flutter and Dart

flutter create my_flutter_app

Navigate into the project directory:

Aug 12, 2024
Read More
Code
javascript

React Custom Hook for API Requests

  • Reusability: The useFetch hook can be used across different components and applications, reducing code duplication and simplifying API interaction.
  • Loading and Error States: Automatically manages loading and error states, providing a consistent way to handle asynchronous operations.
  • Cleanup Handling: Prevents state updates on unmounted components, reducing potential memory leaks and ensuring stability.
  • Custom Headers: Extend the hook to accept custom headers or authentication tokens in the options parameter.
  • Polling: Implement a polling mechanism by setting up a setInterval within the useEffect for periodically fetching data.
  • Data Transformation: Add a callback function to transform the fetched data before setting it in state.

Aug 12, 2024
Read More
Tutorial
css

Building Responsive Web Designs with Tailwind CSS

Add custom colors and fonts to the theme.extend section:

   theme: {
     extend: {
       colors: {
         customBlue: '#1E3A8A',
       },
       fontFamily: {
         sans: ['Helvetica', 'Arial', 'sans-serif'],
       },
     },
   },

Aug 05, 2024
Read More
Note
javascript css +1

Automatically add Tailwind CSS and jQuery classes to any table

  • bg-white divide-y divide-gray-200: White background and row separators.
  • hover:bg-gray-100: Hover effect.

Aug 03, 2024
Read More
Browser Mockup 1
Tailwind Component

Browser Mockup 1

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!