React useEffect – What, Why, and How to Use It

By: H.R.

16/06/2025

React useEffect – What, Why, and How to Use It

useEffect is one of the most powerful and widely used hooks in React. It lets your component interact with the outside world, like APIs, DOM, or even timers.

🧩 1. What is useEffect?

  • useEffect is a React Hook that runs side effects in function components.

  • Common use cases:

    • Fetching data from an API

    • Setting up subscriptions or timers

    • Direct DOM manipulation

    • Running code when props/state change


🔤 Basic Syntax:


import { useEffect } from 'react';


useEffect(() => {

  // your code here

}, [dependencies]);



⚙️ 2. Example: Run on First Render (Component Did Mount)


useEffect(() => {

  console.log("Component mounted");

}, []);


💡 Explanation:

  • Runs only once when the component mounts.

  • The empty [] means "no dependencies", so it won’t run again.


🔁 3. Example: Run When a Value Changes


useEffect(() => {

  console.log("Count changed:", count);

}, [count]);


💡 Explanation:

  • Runs every time count changes.

  • Useful for triggering API calls or re-render logic based on changes.


🧹 4. Example: Cleanup Function


useEffect(() => {

  const timer = setInterval(() => {

    console.log("Tick");

  }, 1000);


  return () => {

    clearInterval(timer);

    console.log("Cleanup done");

  };

}, []);


💡 Explanation:

  • The returned function runs when the component unmounts.

  • Useful to clear timers, event listeners, or subscriptions.


🧠 5. Common Mistakes to Avoid

  • Forgetting dependencies can cause bugs.

  • Overusing useEffect for simple calculations (prefer derived values).

  • Triggering unnecessary re-renders.


🧪 Bonus Tip:

You can have multiple useEffects in one component — each handles its own logic cleanly.