π14. useEffect Hook in React β Full Explanation with Real-Life Example

Table of contents
- β What is useEffect?
- π‘ Why do we use useEffect?
- π§ Syntax of useEffect
- π§ Breakdown:
- π οΈ Real Life Example 1: Change Document Title
- π οΈ Real Life Example 2: Fetch API Data
- π οΈ Real Life Example 3: Set and Clear Timer
- π What is the Dependency Array?
- π§ Summary
- π useEffect Covers These React Concepts:
- π¦ Mini Project: Crypto Tracker App
β
What is useEffect
?
In React, the useEffect
hook lets you perform side effects in your components.
Side effects are operations that interact with the outside world, such as:
Fetching data from an API
Updating the DOM directly
Setting a timer
Listening for keyboard or mouse events
useEffect
replaces lifecycle methods like componentDidMount
, componentDidUpdate
, and componentWillUnmount
from class components.
π‘ Why do we use useEffect?
In real life, when a component is loaded or updated, we often want to do something extra β like getting data from a server or updating the page title.
Thatβs where useEffect
helps us.
π§ Syntax of useEffect
import { useEffect } from 'react';
useEffect(() => {
// code for side-effect
}, [dependencies]);
π§ Breakdown:
The first argument is a function that contains your side effect logic.
The second argument is a dependency array:
Empty array
[]
: runs only once (likecomponentDidMount
)With dependencies
[count]
: runs whenever that variable changesNo array: runs on every render (not recommended usually)
π οΈ Real Life Example 1: Change Document Title
import React, { useState, useEffect } from "react";
function TitleChanger() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]); // Runs every time 'count' changes
return (
<div>
<h2>You clicked {count} times</h2>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
}
π§Ύ Explanation:
When you click the button, count increases.
useEffect
runs again and updates the browser title with the new count.
π οΈ Real Life Example 2: Fetch API Data
import React, { useState, useEffect } from "react";
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => setUsers(data));
}, []); // runs only once
return (
<div>
<h2>User List</h2>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
π§Ύ Explanation:
When the component loads, it fetches data from an API.
The
[]
makes sure it runs only once when the component mounts.
π οΈ Real Life Example 3: Set and Clear Timer
import React, { useEffect, useState } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
// Cleanup
return () => clearInterval(interval);
}, []); // set once
return <h2>Timer: {seconds}s</h2>;
}
π§Ύ Explanation:
A timer starts when the component loads.
Cleanup function ensures that timer stops when component is unmounted.
π What is the Dependency Array?
The second argument in useEffect
is the dependency array:
[count]
β Effect will run only whencount
changes.[]
β Effect will run only once.If no array β Effect runs on every render (not recommended).
βCommon Mistake:
useEffect(() => {
// infinite loop if setState is called without dependency
setCount(count + 1);
});
It will cause infinite re-rendering. Always define dependencies properly.
π§ Summary
Topic | Explanation |
What is useEffect | A Hook to handle side effects |
When to use | Fetching data, timers, updating DOM |
Syntax | useEffect(() => {}, [deps]) |
Dependency array | Controls when the effect runs |
Cleanup function | Used to clean up timers, listeners etc. |
π useEffect Covers These React Concepts:
Hooks (
useEffect
,useState
)API integration
Timers
Cleanup logic
Real-life UI behavior
Absolutely! Here's a real-life mini project using both useState
and useEffect
, written in simple English and structured professionally. This project is a:
π¦ Mini Project: Crypto Tracker App
A simple app to display a list of top cryptocurrencies with their name, symbol, and price β using
useEffect
to fetch data anduseState
to manage state.
π Features:
Uses
useEffect
to fetch data from a public APIUses
useState
to store and display dataUses Bootstrap for responsive styling
Real-life example of how modern apps fetch & show data dynamically
π§ Tech Stack:
React
Hooks:
useState
,useEffect
Bootstrap 5 (CDN-based)
Public API:
https://api.coingecko.com/api/v3/coins/markets
π₯οΈ Final Output Preview:
A responsive table that displays the top 10 cryptocurrencies with their names, symbols, current price, and image.
π Project Structure:
CryptoTrackerApp/
βββ App.js
βββ index.js
βββ App.css (optional)
π» Step-by-Step Code with Explanation
β
Step 1: Setup Bootstrap in index.html
Make sure this is added to your public/index.html
inside <head>
:
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
β Step 2: App.js
import React, { useState, useEffect } from "react";
function App() {
const [coins, setCoins] = useState([]);
useEffect(() => {
// Fetching data from CoinGecko API
fetch(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=false"
)
.then((response) => response.json())
.then((data) => setCoins(data))
.catch((error) => console.error("Error fetching data:", error));
}, []); // Runs only once when the component mounts
return (
<div className="container mt-5">
<h2 className="text-center mb-4">π Crypto Tracker</h2>
<table className="table table-striped table-hover">
<thead className="table-dark">
<tr>
<th>Coin</th>
<th>Symbol</th>
<th>Price (USD)</th>
</tr>
</thead>
<tbody>
{coins.map((coin) => (
<tr key={coin.id}>
<td>
<img
src={coin.image}
alt={coin.name}
style={{ width: "30px", marginRight: "10px" }}
/>
{coin.name}
</td>
<td>{coin.symbol.toUpperCase()}</td>
<td>${coin.current_price.toLocaleString()}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default App;
π§ Explanation:
Part | Description |
useState([]) | Stores fetched coin data |
useEffect() | Runs once on component mount to fetch API data |
fetch() | Calls CoinGecko API and retrieves top 10 coins |
setCoins(data) | Saves data into state for display |
.map() | Loops through each coin and creates a table row |
Bootstrap | Makes layout clean and responsive |
π§ͺ Test the App
Run your React app using:
npm start
Youβll see a Crypto Tracker Table with name, symbol, and price.
Try resizing the browser to see Bootstrap responsiveness.
π React Topics Covered:
β
useState
β
useEffect
β
fetch API
β
JSX rendering with .map()
β
Bootstrap usage in React
β
Real-world use of public APIs
Would you like me to give a second version with search or filter functionality too?
if yes please write in commect section βYES we need projectβ .
π Stay Connected
If you found this article helpful and want to receive more such beginner-friendly and industry-relevant React notes, tutorials, and project ideas β
π© Subscribe to our newsletter by entering your email below.
And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment,
π₯ Donβt forget to subscribe to my YouTube channel β Knowledge Factory 22 β for regular content on tech concepts, career tips, and coding insights!
Stay curious. Keep building. π
Subscribe to my newsletter
Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Payal Porwal
Payal Porwal
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: π In-depth explorations of emerging technologies π‘ Practical tutorials and how-to guides π§Insights on software development best practices πReviews of the latest tools and frameworks π‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Letβs connect and grow together! π