Popular Searches
Popular Course Categories
Popular Courses

useEffect Execution

useEffect Execution

React Side Effects and Lifecycle

useEffect Execution in React JS

useEffect Execution is an important concept in React JS that explains when and how the useEffect() Hook runs during a component's lifecycle. It is commonly used to synchronize components with external systems, such as APIs, timers, event listeners, browser features, and subscriptions.

React JS Training: Explore JustAcademy React JS Training

Course Demo: Register for React JS Course Demo


1. What Is useEffect() in React?

useEffect() is a React Hook that allows function components to synchronize with external systems. An Effect consists of setup logic and, optionally, cleanup logic. React runs the setup after a component commits to the screen, according to the dependency array.

The basic syntax is:

import { useEffect } from "react";
useEffect(() => {
  // Effect setup logic
  return () => {
    // Optional cleanup logic
  };
}, [dependencies]);

Explanation:

  • useEffect() declares an Effect in a function component.
  • The setup function contains the work that needs to run after a commit.
  • The optional cleanup function releases resources or reverses the setup.
  • The dependency array determines when React needs to re-run the Effect.

2. How Does useEffect() Execute?

React first renders a component and commits the necessary changes to the DOM. After the commit, React runs the Effect setup when its execution conditions are met.

Execution Steps

  1. Component rendering: React executes the component function to calculate its UI.
  2. DOM commit: React applies the required changes to the DOM.
  3. Effect setup: React runs the Effect setup after the commit when required.
  4. Dependency comparison: React compares dependency values with those from the previous Effect execution.
  5. Cleanup: If the Effect needs to re-run, React runs its previous cleanup before the next setup.
  6. Re-execution: React runs the new setup using the latest committed values.

Effects are intended for synchronizing with external systems. Calculations that can be performed directly during rendering generally do not need an Effect.

3. useEffect() Without a Dependency Array

When you omit the dependency array, React runs the Effect after every committed render of the component.

Example

import { useEffect, useState } from "react";
function Counter() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log("Effect executed after a commit");
  });
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}
export default Counter;

How It Works

  • When the component first commits, the Effect runs.
  • When the button is clicked, the state changes.
  • React renders the component again and commits the updated UI.
  • The Effect runs again after that commit.

Important: If an Effect updates state on every execution without a stopping condition, it may cause an infinite render loop.

4. useEffect() With an Empty Dependency Array

When you pass an empty dependency array, [], React runs the Effect after the initial client-side commit. Ordinary state or prop changes do not, by themselves, cause that Effect to run again.

Example

import { useEffect } from "react";
function Welcome() {
  useEffect(() => {
    console.log("Welcome component Effect executed");
  }, []);
  return <h1>Welcome to React JS</h1>;
}
export default Welcome;

How It Works

  • The component renders and commits its initial UI.
  • The Effect setup runs after the commit.
  • Ordinary re-renders do not cause the Effect to execute again because its dependency list is empty.
  • When the component is removed, React runs the Effect cleanup if one was returned.

Note: In development Strict Mode, React may run an additional setup-and-cleanup cycle to help identify Effects that are not properly cleaned up.

5. useEffect() With Dependencies

When dependencies are specified, React runs the Effect after the initial commit and runs it again after a commit when one or more dependency values differ from their previous values.

Example

import { useEffect, useState } from "react";
function UserProfile() {
  const [userId, setUserId] = useState(1);
  useEffect(() => {
    console.log("Current user ID:", userId);
  }, [userId]);
  return (
    <div>
      <h2>User ID: {userId}</h2>
      <button onClick={() => setUserId(userId + 1)}>
        Next User
      </button>
    </div>
  );
}
export default UserProfile;

How It Works

  1. The initial render displays User ID 1.
  2. The Effect runs after the initial commit.
  3. Clicking the button updates userId.
  4. React renders and commits the updated UI.
  5. Because userId changed, React runs the Effect again.

6. Understanding the Three Dependency Patterns

Pattern Execution Behavior Typical Use
useEffect(() => {}) Runs after every committed render. Effects that intentionally need to run after each commit.
useEffect(() => {}, []) Runs after the initial client-side commit, with an additional development Strict Mode cycle possible. Setting up a resource that remains active while the component is mounted.
useEffect(() => {}, [value]) Runs after the initial commit and again when a dependency changes. Synchronizing an external system with a particular value.

7. Cleanup Function Execution

A cleanup function is returned from the Effect setup. React runs it before the Effect setup runs again with changed dependencies and when the component is removed.

Example: Timer Cleanup

import { useEffect, useState } from "react";
function Timer() {
  const [seconds, setSeconds] = useState(0);
  useEffect(() => {
    const timerId = setInterval(() => {
      setSeconds(previous => previous + 1);
    }, 1000);
    return () => {
      clearInterval(timerId);
    };
  }, []);
  return <h2>Seconds: {seconds}</h2>;
}
export default Timer;

Explanation

  • The Effect starts a timer after the component's initial commit.
  • The timer updates the seconds state every second.
  • React re-renders the component to show the latest count.
  • The empty dependency array prevents ordinary re-renders from restarting the Effect.
  • When the component unmounts, cleanup clears the timer.

8. useEffect() Execution Order

Consider an Effect with dependencies:

useEffect(() => {
  console.log("Setup:", count);
  return () => {
    console.log("Cleanup:", count);
  };
}, [count]);

In a normal production execution, the sequence is:

  1. Initial commit: The setup runs with the initial count.
  2. State update: The count changes and React commits the updated UI.
  3. Previous cleanup: React runs the cleanup from the previous Effect execution.
  4. New setup: React runs the Effect again with the new count.
  5. Unmount: React runs the final cleanup when the component is removed.

For non-interaction updates, React generally allows the browser to paint before running a passive Effect. Timing can differ for interaction-related updates, so do not rely on useEffect() for precise visual timing.

9. useEffect() and API Calls

A common use of useEffect() is fetching data from an API when a component mounts or when a relevant dependency changes. The example below includes basic loading and error handling.

import { useEffect, useState } from "react";
function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  useEffect(() => {
    const controller = new AbortController();
    async function fetchUsers() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users",
          { signal: controller.signal }
        );
        if (!response.ok) {
          throw new Error("Failed to fetch users");
        }
        const data = await response.json();
        setUsers(data);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message);
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }
    fetchUsers();
    return () => controller.abort();
  }, []);
  if (loading) return <p>Loading users...</p>;
  if (error) return <p>Error: {error}</p>;
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}
export default Users;

Explanation: The Effect requests user data after the initial commit. The loading state indicates progress, and the error state displays a failure message. The cleanup aborts an unfinished request if the component is removed.

Important: An Effect is not a guarantee that an API request will happen only once in every development environment. Strict Mode may run an additional setup-and-cleanup cycle. For larger applications, consider a framework's data-fetching features or a dedicated data-fetching library.

10. Difference Between useEffect() and useLayoutEffect()

Both Hooks let components synchronize with external systems, but they differ in timing.

Feature useEffect() useLayoutEffect()
Timing Runs after a commit; often after the browser paints. Runs after DOM mutations but before the browser repaints.
Common use API synchronization, subscriptions, timers. Measuring layout or applying visual changes that must happen before repaint.
Performance Usually preferable for ordinary Effects. Can block painting, so use only when necessary.
Visual measurement May allow a visible intermediate frame. Useful when layout must be measured before repaint.

11. Common Mistakes in useEffect() Execution

  • Missing dependencies: Omitting reactive values used by an Effect may lead to stale values.
  • Infinite loops: Updating state on every Effect execution without a suitable condition may cause repeated renders.
  • Missing cleanup: Timers, subscriptions, and event listeners may continue running after they are no longer needed.
  • Unnecessary Effects: Avoid using Effects for simple calculations that can be derived during rendering.
  • Incorrect dependency assumptions: Objects and functions created during rendering can have new references on each render, potentially causing Effects to re-run.
  • Expecting exactly one execution in development: Strict Mode can intentionally perform an extra setup-and-cleanup cycle.
  • Using useEffect() for every event: User-triggered actions such as submitting a form generally belong in event handlers rather than in Effects triggered indirectly by state changes.

12. Best Practices for useEffect()

  • Include all required reactive dependencies in the dependency array.
  • Write cleanup logic for resources created by an Effect.
  • Keep Effect setup and cleanup symmetrical.
  • Use functional state updates when the next value depends on the previous state.
  • Use AbortController or another suitable cancellation strategy for asynchronous work when appropriate.
  • Do not suppress dependency warnings without understanding the reason.
  • Use useLayoutEffect() only when work must happen before the browser repaints.
  • Test the component in development Strict Mode to catch cleanup issues.

13. Practical Example: Tracking Effect Execution

import { useEffect, useState } from "react";
function EffectDemo() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log("Effect setup:", count);
    return () => {
      console.log("Effect cleanup:", count);
    };
  }, [count]);
  return (
    <div>
      <h1>useEffect Execution Demo</h1>
      <p>Count: {count}</p>
      <button onClick={() => setCount(previous => previous + 1)}>
        Increase Count
      </button>
    </div>
  );
}
export default EffectDemo;

Expected Result

  • Initially, the Effect setup runs with count 0.
  • After clicking the button, React commits the updated count.
  • The cleanup from the previous Effect runs, followed by the new setup.
  • When the component unmounts, the last cleanup runs.

Development Strict Mode may introduce an additional setup-and-cleanup cycle, so the console output can contain extra messages during development.

14. Interview Questions and Answers

Q1. What is useEffect() in React?

useEffect() is a Hook used to synchronize a component with external systems after a commit.

Q2. When does useEffect() run?

It runs after a commit when its dependency conditions are met. Without a dependency array, it runs after every committed render.

Q3. What does an empty dependency array mean?

An empty dependency array means the Effect does not re-run because of ordinary prop or state changes. It runs after the initial client-side commit, subject to development Strict Mode behavior.

Q4. What happens when a dependency changes?

After the updated commit, React runs the previous cleanup if present and then runs the Effect setup again.

Q5. Why is a cleanup function required?

Cleanup releases resources such as timers, event listeners, and subscriptions and can cancel unfinished asynchronous work.

Q6. Can useEffect() cause an infinite loop?

Yes. An Effect that updates state on every execution can trigger repeated renders, especially when it has no dependency array or depends on a value that changes on each render.

Q7. What is the difference between useEffect() and useLayoutEffect()?

useEffect() is appropriate for most synchronization tasks. useLayoutEffect() runs before repaint and is useful for layout measurements or visual changes that must happen before the browser paints.

Q8. Does useEffect() run during server-side rendering?

No. Effects run on the client, not during server rendering.

15. Quick Revision Checklist

  • Understand the purpose and syntax of useEffect().
  • Know the difference between no dependency array, an empty array, and a dependency list.
  • Understand the order of setup and cleanup.
  • Practice fetching API data inside an Effect.
  • Understand React Strict Mode's additional development checks.
  • Learn to prevent infinite loops and stale dependency values.
  • Know when to choose useEffect() versus useLayoutEffect().

16. Conclusion

Understanding useEffect execution helps React developers control when external synchronization takes place and how resources are managed across component updates. By learning dependency arrays, cleanup functions, API requests, and Strict Mode behavior, developers can write reliable, efficient, and maintainable React applications.


Learn React JS with JustAcademy

Build your React JS knowledge through structured learning, practical examples, and hands-on projects.

Explore JustAcademy React JS Training Course

Register for a React JS Course Demo

Previous Next
whatsapp