Mastering React's `useEffect`: A Guide to Side Effects and Real-World Applications

Aditi DubeyAditi Dubey
2 min read

If you're learning React, you've likely seen the useEffect hook and maybe been a little confused by it.

In this blog, I’ll explain:

  • What useEffect does,

  • Why it's important,

  • And 3 real-world examples where you’ll use it in your React apps.

By the end, you’ll have a clear understanding and confidence to use useEffect in your own projects!


🧩 What is useEffect?

In simple terms, useEffect lets you perform side effects in your component - like fetching data, updating the DOM, or setting up a timer.

It’s the React way of saying:
👉 “Do something after the component has rendered.”

jsCopyEditimport { useEffect } from 'react';

useEffect(() => {
  // your side-effect code here
}, [dependencies]);

🔁 Use Case 1: Running Code on Component Mount

Let’s say you want to show a message in the console when your component loads.

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

The empty array ([]) means this effect runs only once just like componentDidMount in class components.


🌐 Use Case 2: Fetching Data from an API

jsCopyEdituseEffect(() => {
  fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(data => setData(data));
}, []);

Here, you make a network request when the component loads. It's a very common use case in real apps.


📦 Use Case 3: Reacting to State Changes

jsCopyEdituseEffect(() => {
  console.log("Counter updated to:", count);
}, [count]);

This effect runs every time count changes useful for triggering actions when state updates.


🧼 Bonus: Cleaning Up with useEffect

If you set up timers or subscriptions, clean them up to avoid memory leaks:

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

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

✅ Summary

  • useEffect is for side effects things that happen outside the normal render.

  • It can run once, on every render, or when specific values change.

  • You must understand this hook if you're building real React apps.


📌 Follow-Up

If you found this helpful, follow me here on Hashnode for more frontend tips!

Next up: useState simplified, or how to build your own custom hook 🔧

0
Subscribe to my newsletter

Read articles from Aditi Dubey directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aditi Dubey
Aditi Dubey