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
- Setting Up a New React Project
- Syntax of
useEffect - 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
- Conclusion
Setting Up a New React Project
First, let’s create a new React project using the create-react-app tool.
- Open your terminal and run the following command:
npx create-react-app usereffect-employee-app - 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
useEffecthook 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
- Open the project directory in your code editor.
- Remove the default content from
src/App.jsandsrc/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
- Create a new file named
Employee.jsin thesrcdirectory. - Define the
Employeecomponent:// 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
useStatehook to manage the list of employees and the loading state. - The
useEffecthook fetches employee data from an API when the component mounts. The empty array[]as the second argument ensures the effect runs only once.
- We use the
- Create a CSS file named
Employee.cssto 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
- API Call: The
useEffecthook is used to fetch data from the API. The data is then set in theemployeesstate, and theloadingstate is updated.useEffect(() => { fetch('https://jsonplaceholder.typicode.com/users') .then((response) => response.json()) .then((data) => { setEmployees(data); setLoading(false); }); }, []);
Displaying the List of Employees
- Map through Employees: The
employeesarray 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
- 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
useEffecthook, 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.