DEV Community

swetha palani
swetha palani

Posted on

useEffect in React

What is useEffect?

useEffect is a React hook that lets you perform side effects in your components.
Side effects are things like:

  • Fetching data from an API
  • Updating the DOM manually
  • Setting up a timer
  • Logging data

It runs after the component renders.

syntax useEffect

Basic Syntax

useEffect(() => {
  // code to run (side effect)
});
Enter fullscreen mode Exit fullscreen mode
  • Runs after every render by default.

Run only once (on mount)

useEffect(() => {
  // code to run once
}, []);
Enter fullscreen mode Exit fullscreen mode
  • Empty dependency array [] → runs only when component mounts.

Run on specific state or prop change

useEffect(() => {
  // code to run when `variable` changes
}, [variable]);
Enter fullscreen mode Exit fullscreen mode
  • variable → dependency, runs only when this changes.

Cleanup function (optional)

useEffect(() => {
  // setup code
  return () => {
    // cleanup code (like unsubscribing, clearing timers)
  };
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

When to use useEffect

  1. When you want something to happen after render.
  2. When you want to watch for changes in a variable (state or props).
  3. When you want to clean up resources (like timers, subscriptions) when a component unmounts.

Where to use

  • Inside a functional component.

Simple Code Example

import React, { useState, useEffect } from "react";

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

  // useEffect runs after every render by default
  useEffect(() => {
    console.log("Count changed:", count);
  }, [count]); // dependency array

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

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • useEffect(() => {...}, [count]) → Runs only when count changes.
  • Without [count], it runs after every render.
  • With [] (empty array), it runs only once when the component mounts.

Top comments (0)