Lesson 16 — useEffect Hook Explained (With Examples)

Introduction 😊

So far, you’ve learned how to manage state using the useState hook.
But many times, React components need to perform actions like:

  • Fetching data from an API 🌐
  • Updating the document title 🧾
  • Running code when a component loads or updates 🔄

These actions are called side effects.

To handle side effects in React, we use the useEffect hook ⚛️

In this lesson, you will learn:

  • What useEffect is
  • Why useEffect is needed
  • How useEffect works
  • Dependency array explained
  • Common useEffect patterns
  • Beginner mistakes to avoid

Let’s begin 🚀


What Is useEffect? 🤔

useEffect is a React Hook that lets you run side effects in function components.

👉 In simple words:

useEffect runs some code after the component renders.

Side effects include:

  • API calls
  • Timers
  • DOM updates
  • Logging data

Why useEffect Is Important 🧠

Before hooks, side effects were handled using lifecycle methods in class components like:

  • componentDidMount
  • componentDidUpdate
  • componentWillUnmount

useEffect replaces all of these with one clean API


Basic Syntax of useEffect 📌

useEffect(() => {
  // side effect code
}, []);

It takes two arguments:

  1. A function (effect)
  2. A dependency array

Example 1: useEffect Runs on Every Render 🔁

import { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("Component rendered");
  });

  return <h1>Hello React</h1>;
}

👉 Runs after every render (initial + updates).


Example 2: useEffect Runs Only Once (Component Mount) 🟢

useEffect(() => {
  console.log("Component mounted");
}, []);

📌 Empty dependency array []
👉 Runs only once, when the component loads.


Example 3: useEffect with Dependency 🔄

import { useState, useEffect } from "react";

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

  useEffect(() => {
    console.log("Count changed:", count);
  }, [count]);

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

👉 useEffect runs only when count changes.


Understanding Dependency Array 🧩

Dependency ArrayBehavior
No arrayRuns on every render
Empty []Runs once
[value]Runs when value changes

👉 This is the most important concept of useEffect.


Example 4: Fetching Data with useEffect 🌐

useEffect(() => {
  fetch("https://api.example.com/users")
    .then(res => res.json())
    .then(data => console.log(data));
}, []);

👉 API call runs once when component loads.


Cleanup Function in useEffect 🧹

Some effects need cleanup (timers, subscriptions).

useEffect(() => {
  const timer = setInterval(() => {
    console.log("Running...");
  }, 1000);

  return () => {
    clearInterval(timer);
  };
}, []);

👉 Cleanup runs when component unmounts.


Common Mistakes Beginners Make ❌

  • Forgetting dependency array
  • Adding wrong dependencies
  • Infinite loops in useEffect
  • Using useEffect unnecessarily

💡 Always think:

When should this effect run?


When Should You Use useEffect? 🤔

Use useEffect when:

  • You need side effects
  • You fetch data
  • You sync with external systems

Do NOT use useEffect for:

  • Simple calculations
  • Rendering UI logic

Conclusion 🎯

The useEffect hook is essential for handling side effects in React.

Key takeaways:

  • useEffect runs after rendering
  • Dependency array controls execution
  • Empty array = run once
  • Cleanup prevents memory leaks
  • useEffect replaces lifecycle methods

👉 Master useEffect, and you unlock real-world React apps 💙


Frequently Asked Questions (FAQs) ❓

Is useEffect mandatory?

No, but it’s required for side effects.

Can we use multiple useEffect hooks?

Yes. It’s recommended to separate concerns.

Does useEffect run before render?

No. It runs after render.


What’s Next? 🚀

👉 In the next lesson, we will learn:

Lesson 17 — useContext Hook Explained
Sharing data globally without prop drilling.

Leave a Comment