What is useEffect hook in react?

In React, you use the useEffect hook to:

  • Run code when a component mounts
  • Run code when a variable changes
  • Do things like:
    • Fetch data from APIs
    • Set up event listeners
    • Update the page title
    • Work with timers

✅ Basic useEffect Example

import { useEffect } from "react";

function Welcome() {
  useEffect(() => {
    console.log("Component loaded (mounted)");
  }, []); // empty array = run only once

  return <h2>Welcome!</h2>;
}

🔍 Explanation

  • useEffect(() => {...}, [])
    • Runs the function once, after the first render.
    • This is like componentDidMount in class components.

✅ useEffect with Dependencies

import { useState, useEffect } from "react";

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

  useEffect(() => {
    console.log("Count changed to:", count);
  }, [count]); // runs whenever `count` changes

  return (
    <div>
      <p>Count is {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

✅ Cleanup with useEffect (Like componentWillUnmount)

useEffect(() => {
  console.log("Component mounted");

  return () => {
    console.log("Component will unmount");
  };
}, []);

This is used to clean up:

  • Intervals
  • Event listeners
  • Subscriptions

✅ Real Example: Timer

import { useState, useEffect } from "react";

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds((prev) => prev + 1);
    }, 1000);

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

  return <h2>Timer: {seconds} sec</h2>;
}

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *