πŸ”14. useEffect Hook in React – Full Explanation with Real-Life Example

Payal PorwalPayal Porwal
6 min read

βœ… 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 (like componentDidMount)

    • With dependencies [count]: runs whenever that variable changes

    • No 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 when count 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

TopicExplanation
What is useEffectA Hook to handle side effects
When to useFetching data, timers, updating DOM
SyntaxuseEffect(() => {}, [deps])
Dependency arrayControls when the effect runs
Cleanup functionUsed 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 and useState to manage state.


πŸš€ Features:

  • Uses useEffect to fetch data from a public API

  • Uses useState to store and display data

  • Uses Bootstrap for responsive styling

  • Real-life example of how modern apps fetch & show data dynamically


πŸ”§ Tech Stack:


πŸ–₯️ 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:

PartDescription
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
BootstrapMakes layout clean and responsive

πŸ§ͺ Test the App

  1. Run your React app using:

     npm start
    
  2. You’ll see a Crypto Tracker Table with name, symbol, and price.

  3. 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. πŸš€

0
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! 🌟