What Is useEffect and When to Use It
×


What Is useEffect and When to Use It

599

🔍 Introduction to useEffect

In React, functional components are the go-to structure — but what if you need to run code when your component loads, updates, or unmounts? That’s where the useEffect hook steps in! It's React’s way of handling side effects, replacing lifecycle methods like componentDidMount and componentDidUpdate from class components.

⚡ What Is useEffect?

useEffect is a hook in React that lets you perform side effects in your components. Side effects can include data fetching, setting up event listeners, interacting with localStorage, or manually updating the DOM.


import { useEffect } from "react";

useEffect(() => {
  console.log("Component mounted or updated!");
});

Key concept: useEffect() takes two arguments — a function and a dependency array.

🛠️ Syntax of useEffect


useEffect(() => {
  // side effect logic here
  return () => {
    // optional cleanup logic
  };
}, [dependencies]);
  • Callback Function: Runs after every render (or specific state/prop changes).
  • Cleanup Function: (Optional) Runs before the component unmounts or before the next effect re-run.
  • Dependencies Array: Determines when the effect runs.

📦 When to Use useEffect

📥 1. Fetching Data from an API


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

The empty array [] means this effect runs only once — when the component mounts, just like componentDidMount.

🕹️ 2. Listening to Events


useEffect(() => {
  const handleResize = () => {
    setWindowWidth(window.innerWidth);
  };

  window.addEventListener("resize", handleResize);

  return () => {
    window.removeEventListener("resize", handleResize);
  };
}, []);

Here, we register a resize event listener and clean it up when the component unmounts.

💾 3. Working with localStorage


useEffect(() => {
  const savedTasks = JSON.parse(localStorage.getItem("tasks"));
  if (savedTasks) {
    setTasks(savedTasks);
  }
}, []);

This is a perfect use case for initializing state with saved data on first render.

🎯 4. Reacting to State or Prop Changes


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

This effect only runs when the count variable changes. It's useful for syncing effects with specific values.

🧹 5. Cleaning Up on Unmount


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

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

Cleanups prevent memory leaks by stopping timers, listeners, or subscriptions when your component unmounts.

⚠️ Common Mistakes to Avoid

  • ❌ Forgetting the dependency array – leads to infinite re-renders.
  • ❌ Not including all dependencies – causes stale or incorrect behavior.
  • ❌ Performing updates inside the effect without checks – can cause loops.

🚀 Final Thoughts

The useEffect hook is an essential tool in every React developer’s toolbox. Whether you’re fetching data, syncing state with the DOM, or managing timers, useEffect helps keep your component logic clean and reactive. Mastering it takes some practice, but once you get the hang of it, you’ll unlock a powerful way to handle side effects in your apps! ⚙️🔥



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat