Hack Frontend Community

How useEffect Works in React?

useEffect is a hook in React that allows performing side effects in functional components. Side effects can include operations such as server requests, event subscriptions, DOM manipulations and much more.

How Does useEffect Work?

useEffect executes after component renders. It allows you to perform actions that shouldn't block rendering, such as asynchronous requests or updates that should occur after render.

Basic Syntax

useEffect(() => {
  // Side effect code
}, [dependencies]);
  • First argument is function with side effect that will be executed after component render.
  • Second argument is dependencies array. If dependencies array isn't passed, effect will execute after every render. If array is empty, effect will execute only once — when component mounts.

useEffect Usage Example

import { useState, useEffect } from "react";

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

  // Start timer when component mounts
  useEffect(() => {
    const intervalId = setInterval(() => {
      setSeconds((prevSeconds) => prevSeconds + 1);
    }, 1000);

    // Clean up effect when component unmounts
    return () => clearInterval(intervalId);
  }, []); // Empty array — effect will execute only once

  return (
    <div>
      <p>Time elapsed: {seconds} seconds</p>
    </div>
  );
}

When Does useEffect Execute?

  • After first render. If no dependencies or array is empty, effect will execute once after component mounts.
  • After every render, if dependencies are passed in array. Hook will execute every time state or props specified in dependencies array change.
  • For effect cleanup. Function returned from useEffect is used to clean up effect, for example, canceling subscriptions or timers.

Example with Dependencies

import { useState, useEffect } from "react";

function FetchData() {
  const [data, setData] = useState(null);
  const [url, setUrl] = useState("https://api.example.com/data");

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(url);
      const result = await response.json();
      setData(result);
    };

    fetchData();
  }, [url]); // Hook will fire when `url` changes

  return (
    <div>
      <button onClick={() => setUrl("https://api.example.com/new-data")}>
        Load new data
      </button>
      <p>{data ? JSON.stringify(data) : "Loading..."}</p>
    </div>
  );
}
  • array not specified: effect runs on every render
  • empty array: effect runs only on mount
  • array with elements: effect runs when any element changes

Effect Cleanup

If hook requires cleanup (e.g., when working with subscriptions or timers), you can return function from useEffect:

useEffect(() => {
  const intervalId = setInterval(() => {
    console.log("Timer working...");
  }, 1000);

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

Using useEffect:

useEffect allows handling side effects in functional components, improving state and resource management in React applications.