React useEffect Hook

Introduction

In this chapter, we will explore the useEffect hook in React. This hook allows you to perform side effects in functional components, such as fetching data, directly interacting with the DOM, and setting up subscriptions or timers. We will create a new React project from scratch, explain the syntax of useEffect, and walk through a real-time project step by step to demonstrate its usage.

Table of Contents

  1. Setting Up a New React Project
  2. Syntax of useEffect
  3. Real-Time Project: Employee Management System
    • Project Setup
    • Creating the Employee Component
    • Adding State to Manage Employees
    • Fetching Employees from an API
    • Displaying the List of Employees
    • Cleanup with useEffect
  4. Conclusion

Setting Up a New React Project

First, let’s create a new React project using the create-react-app tool.

  1. Open your terminal and run the following command:
    npx create-react-app usereffect-employee-app
    
  2. Navigate to the project directory:
    cd usereffect-employee-app
    

Syntax of useEffect

The useEffect hook lets you perform side effects in functional components. It accepts a function (the effect) and an optional array of dependencies. The effect function is executed after every render by default, but you can control when it runs by specifying dependencies.

Syntax

useEffect(() => {
  // effect
  return () => {
    // cleanup
  };
}, [dependencies]);
  • effect: The function that contains the side effect code.
  • cleanup: Optional function to clean up after the effect (e.g., removing event listeners).
  • dependencies: Optional array of dependencies that control when the effect runs.

Example

import React, { useState, useEffect } from 'react';

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setCount((prevCount) => prevCount + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <p>Timer: {count} seconds</p>
    </div>
  );
}

export default Timer;

Explanation:

  • The useEffect hook sets up an interval that increments the count every second.
  • The cleanup function clears the interval when the component unmounts to prevent memory leaks.

Real-Time Project: Employee Management System

Project Setup

  1. Open the project directory in your code editor.
  2. Remove the default content from src/App.js and src/App.css:
    // src/App.js
    import React from 'react';
    import './App.css';
    import Employee from './Employee';
    
    function App() {
      return (
        <div className="App">
          <h1>Employee Management System</h1>
          <Employee />
        </div>
      );
    }
    
    export default App;
    
    /* src/App.css */
    .App {
      text-align: center;
      padding: 20px;
    }
    
    h1 {
      margin-bottom: 20px;
    }
    

Creating the Employee Component

  1. Create a new file named Employee.js in the src directory.
  2. Define the Employee component:
    // src/Employee.js
    import React, { useState, useEffect } from 'react';
    import './Employee.css';
    
    function Employee() {
      const [employees, setEmployees] = useState([]);
      const [loading, setLoading] = useState(true);
    
      useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/users')
          .then((response) => response.json())
          .then((data) => {
            setEmployees(data);
            setLoading(false);
          });
      }, []);
    
      return (
        <div className="container mt-5">
          <h2>Employee List</h2>
          {loading ? (
            <p>Loading...</p>
          ) : (
            <ul className="list-group">
              {employees.map((employee) => (
                <li key={employee.id} className="list-group-item">
                  {employee.id} - {employee.name} ({employee.email})
                </li>
              ))}
            </ul>
          )}
        </div>
      );
    }
    
    export default Employee;
    

    Explanation:

    • We use the useState hook to manage the list of employees and the loading state.
    • The useEffect hook fetches employee data from an API when the component mounts. The empty array [] as the second argument ensures the effect runs only once.
  3. Create a CSS file named Employee.css to style the Employee component:
    /* src/Employee.css */
    .container {
      max-width: 600px;
      margin: 0 auto;
      text-align: left;
    }
    
    .list-group-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      margin-bottom: 10px;
    }
    

Fetching Employees from an API

  1. API Call: The useEffect hook is used to fetch data from the API. The data is then set in the employees state, and the loading state is updated.
    useEffect(() => {
      fetch('https://jsonplaceholder.typicode.com/users')
        .then((response) => response.json())
        .then((data) => {
          setEmployees(data);
          setLoading(false);
        });
    }, []);
    

Displaying the List of Employees

  1. Map through Employees: The employees array is mapped to display each employee in an unordered list (<ul>).
    <ul className="list-group">
      {employees.map((employee) => (
        <li key={employee.id} className="list-group-item">
          {employee.id} - {employee.name} ({employee.email})
        </li>
      ))}
    </ul>
    

Cleanup with useEffect

  1. Cleanup Function: If you were to add event listeners or timers, you would include a cleanup function to remove them when the component unmounts. Here’s an example using a timer:
    useEffect(() => {
      const timer = setInterval(() => {
        console.log('Timer running');
      }, 1000);
    
      return () => clearInterval(timer);
    }, []);
    

Explanation:

  • The cleanup function, returned by the useEffect hook, clears the interval when the component unmounts to prevent memory leaks.

Conclusion

In this chapter, we created a new React project and explored the useEffect hook. We learned the syntax of useEffect and walked through a real-time project step by step to create an Employee Management System application. By understanding and using the useEffect hook, you can perform side effects in your functional components, making your React applications more dynamic and interactive.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top