React introduced Hooks in version 16.8, and one of the most commonly used Hooks is useEffect(). The useEffect() Hook lets us perform side effects in function components, such as fetching data, updating the DOM, or setting up subscriptions.
How useEffect() Works
TheuseEffect()Hook accepts two arguments:
- A function: This is the effect that will run. This function is executed after the component renders (or re-renders). You can think of this as the "side effect" logic.
- An optional dependency array: This tells React when to re-run the effect. If you provide an empty array ([]), the effect will only run once, after the initial render.
Basic Syntax:
useEffect(() => {
// Your side effect code here
}, [dependencies]);
Example 1: Fetching Data
import React, { useEffect, useState } from "react";
function DataFetchingComponent() {
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
// Fetch data from an API
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((json) => setData(json))
.catch((err) => setError("Error fetching data"));
}, []);
return (
<div style={{ maxWidth: "1200px", margin: "0 auto", padding: "20px" }}>
<h1 style={{ textAlign: "center", marginBottom: "20px", color: "#333" }}>
Users Data
</h1>
<h2 style={{ textAlign: "center", marginBottom: "20px", color: "#333" }}>
Understanding the useEffect() Hook in React By Sudhanshu Gaikwad
</h2>
{error ? (
<p style={{ color: "red", textAlign: "center" }}>{error}</p>
) : (
<table
style={{
width: "100%",
borderCollapse: "collapse",
marginBottom: "20px",
}}
>
<thead style={{ backgroundColor: "black", color: "white" }}>
<tr>
<th style={{ padding: "10px", textAlign: "left" }}>ID</th>
<th style={{ padding: "10px", textAlign: "left" }}>Name</th>
<th style={{ padding: "10px", textAlign: "left" }}>Username</th>
<th style={{ padding: "10px", textAlign: "left" }}>Email</th>
</tr>
</thead>
<tbody>
{data.map((user) => (
<tr
key={user.id}
style={{
backgroundColor: user.id % 2 === 0 ? "#f2f2f2" : "white",
borderBottom: "1px solid #ddd",
}}
>
<td style={{ padding: "10px" }}>{user.id}</td>
<td style={{ padding: "10px" }}>{user.name}</td>
<td style={{ padding: "10px" }}>{user.username}</td>
<td style={{ padding: "10px" }}>{user.email}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
export default DataFetchingComponent;
Output
Example 2: Setting up a Timer
import React, { useState, useEffect } from "react";
function TimerComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCount((prevCount) => prevCount + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100vh", backgroundColor: "#f0f4f8" }}>
<div style={{ backgroundColor: "#fff", borderRadius: "10px", padding: "30px 50px", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)", textAlign: "center" }}>
<h1 style={{ fontSize: "3rem", fontFamily: "Roboto, sans-serif", color: "#333", margin: "0" }}>{count} seconds</h1>
<p style={{ marginTop: "15px", fontSize: "1.2rem", color: "#666" }}>Timer running with useEffect hook</p>
</div>
</div>
);
}
export default TimerComponent;
Output
To summarize:
- Use
useEffect()for tasks like fetching data, manipulating the DOM, or setting up timers. - You can control when the effect runs by passing a dependency array.
- Always clean up effects when necessary by returning a function from the
useEffect()callback.


Top comments (0)