Popular Searches
Popular Course Categories
Popular Courses

Effect Dependency Arrays

Effect Dependency Arrays

React Side Effects and Lifecycle

Effect Dependency Arrays in React JS

Effect Dependency Arrays are an important concept in React JS that determines when the useEffect() Hook should execute again. They help developers control side effects such as API requests, event listeners, timers, subscriptions, and synchronization with external systems.

Understanding dependency arrays helps prevent unnecessary Effect executions, stale values, and infinite render loops while building efficient React applications.

React JS Training: Explore JustAcademy React JS Training

Course Demo: Register for React JS Course Demo


1. What Is a Dependency Array in React?

A dependency array is an array of values passed as the second argument to the useEffect() Hook. React compares the dependency values from the current render with those from the previous render to determine whether an Effect needs to run again.

Basic Syntax:

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

Explanation:

  • useEffect() declares an Effect in a function component.
  • The first argument is the Effect setup function.
  • The optional cleanup function releases resources or reverses the setup.
  • The second argument is the dependency array.
  • React compares each dependency using Object.is().

2. Why Are Dependency Arrays Important?

Dependency arrays help React determine when an Effect must synchronize again with an external system. They are particularly useful when an Effect depends on changing props, state, or values calculated inside a component.

Benefits of dependency arrays include:

  • Controlling when an Effect runs again.
  • Keeping external systems synchronized with the latest values.
  • Avoiding unnecessary API requests or subscriptions.
  • Reducing the risk of using outdated values inside an Effect.
  • Helping developers write predictable and maintainable components.
  • Supporting correct cleanup and resource management.

3. Types of Dependency Arrays

There are three common dependency patterns used with useEffect().

Dependency Pattern Execution Behavior Typical Use
No dependency array Runs after every committed render. Effects that intentionally need to run after every commit.
Empty dependency array [] Runs after the initial client-side commit; development Strict Mode may run an additional setup-and-cleanup cycle. Setting up a resource that remains active while the component is mounted.
Array with dependencies [value] Runs after the initial commit and again when a dependency changes. Synchronizing with an external system using changing values.

4. useEffect Without a Dependency Array

When the dependency array is omitted, 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 Count
      </button>
    </div>
  );
}
export default Counter;

How It Works

  1. The component renders and commits its initial UI.
  2. The Effect runs after the initial commit.
  3. Clicking the button updates the state.
  4. React renders and commits the updated UI.
  5. The Effect runs again after the updated commit.

Important: If the Effect updates state on every execution, it may cause repeated renders or an infinite loop.

5. useEffect With an Empty Dependency Array

An empty dependency array tells React that the Effect has no reactive dependencies that should trigger re-execution. The Effect runs after the initial client-side commit and does not re-run because of ordinary state or prop changes alone.

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 for the first time.
  • React commits the initial UI.
  • The Effect runs after the commit.
  • Subsequent state changes do not make this Effect run again.
  • If a cleanup function exists, React runs it when the component unmounts.

Note: In development Strict Mode, React can perform an additional setup-and-cleanup cycle to help detect missing cleanup logic. Therefore, do not rely on an Effect running exactly once in every environment.

6. useEffect With a Single Dependency

A dependency array containing one value causes the Effect to run after the initial commit and again after a commit when that value changes.

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;

Explanation

  1. The initial value of userId is 1.
  2. The Effect runs after the initial commit.
  3. When the button is clicked, the state changes.
  4. React commits the updated UI with the new user ID.
  5. Since userId has changed, the Effect runs again.

7. useEffect With Multiple Dependencies

An Effect can depend on multiple values. React compares every dependency with its previous value. If at least one dependency changes, the Effect runs again after the updated commit.

Example

import { useEffect, useState } from "react";
function ProductDetails() {
  const [productId, setProductId] = useState(1);
  const [category, setCategory] = useState("electronics");
  useEffect(() => {
    console.log("Product ID:", productId);
    console.log("Category:", category);
  }, [productId, category]);
  return (
    <div>
      <p>Product ID: {productId}</p>
      <p>Category: {category}</p>
      <button onClick={() => setProductId(productId + 1)}>
        Next Product
      </button>
      <button onClick={() => setCategory("fashion")}>
        Change Category
      </button>
    </div>
  );
}
export default ProductDetails;

Explanation

  • The Effect runs after the initial commit.
  • Changing the product ID causes the Effect to run again.
  • Changing the category also causes the Effect to run again.
  • If neither dependency changes, ordinary re-renders do not cause this Effect to re-run.

8. How React Compares Dependencies

React compares each dependency with its corresponding value from the previous render using Object.is(). If a dependency differs, React schedules the Effect to re-run after the relevant commit.

Example With a Primitive Value

useEffect(() => {
  console.log("Count changed:", count);
}, [count]);

Numbers, strings, and booleans are primitive values. If the new value is the same as the previous value according to Object.is(), that dependency does not trigger the Effect to re-run.

Example With an Object

import { useEffect } from "react";
function UserDetails({ name }) {
  const user = { name: name };
  useEffect(() => {
    console.log("User object changed:", user);
  }, [user]);
  return <p>User: {name}</p>;
}
export default UserDetails;

Explanation: The user object is created again on every render. Its reference is different from the previous object, so the Effect may run after every committed render.

To avoid unnecessary re-execution, consider depending on the specific primitive values needed by the Effect or creating the object inside the Effect when appropriate.

9. Dependency Arrays and State Updates

State values used by an Effect are often included in the dependency array. When a dependency changes, React re-runs the Effect to synchronize with the new value.

Example

import { useEffect, useState } from "react";
function SearchBox() {
  const [searchTerm, setSearchTerm] = useState("");
  useEffect(() => {
    console.log("Search term:", searchTerm);
  }, [searchTerm]);
  return (
    <input
      value={searchTerm}
      onChange={event => setSearchTerm(event.target.value)}
      placeholder="Enter search term"
    />
  );
}
export default SearchBox;

Explanation: Each time the user enters a different search term, React updates the state, commits the new UI, and runs the Effect again.

For real search applications, consider debouncing requests so the application does not send a request for every keystroke.

10. Dependency Arrays and API Requests

Dependency arrays can be used to fetch data when a component mounts or when a relevant parameter changes. For example, an API request may depend on a product ID or user ID.

Example: Fetch Product Information

import { useEffect, useState } from "react";
function Product({ productId }) {
  const [product, setProduct] = useState(null);
  const [error, setError] = useState("");
  useEffect(() => {
    const controller = new AbortController();
    async function fetchProduct() {
      setProduct(null);
      setError("");
      try {
        const response = await fetch(
          `https://dummyjson.com/products/${productId}`,
          { signal: controller.signal }
        );
        if (!response.ok) {
          throw new Error("Unable to fetch product");
        }
        const data = await response.json();
        setProduct(data);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message);
        }
      }
    }
    fetchProduct();
    return () => controller.abort();
  }, [productId]);
  if (error) return <p>{error}</p>;
  if (!product) return <p>Loading product...</p>;
  return <h2>{product.title}</h2>;
}
export default Product;

Explanation

  • The component receives a productId prop.
  • The Effect runs after the initial commit.
  • The API request retrieves the product matching that ID.
  • When productId changes, the previous request is aborted if it is still in progress and a new request is started.
  • The cleanup helps prevent unnecessary work from an outdated request.

11. Dependency Arrays and Cleanup Functions

Cleanup functions work together with dependency arrays. When dependencies change, React runs the previous cleanup before running the next Effect setup. React also runs cleanup when the component unmounts.

Example

import { useEffect, useState } from "react";
function WindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }
    window.addEventListener("resize", handleResize);
    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);
  return <h2>Window Width: {width}px</h2>;
}
export default WindowWidth;

Explanation: The Effect registers a resize event listener. Its cleanup removes the listener when the component unmounts. This example assumes it runs in a browser environment; server-rendered applications need to account for the absence of window during server rendering.

12. Common Dependency Array Mistakes

  • Missing dependencies: Using a reactive value inside an Effect without including it can result in stale values.
  • Unnecessary dependencies: Including unstable object or function references may cause the Effect to run more often than expected.
  • Empty array misuse: Using [] does not make an Effect automatically respond to changing props or state.
  • Infinite loops: Updating a dependency inside an Effect on every execution may cause repeated renders.
  • Incorrect dependency order or length: Keep the dependency list inline and ensure its number and order of items remain constant.
  • Mutating objects: Changing an object without creating a new reference may prevent React from detecting the change as expected.
  • Ignoring cleanup: Missing cleanup can leave timers, subscriptions, or event listeners active unnecessarily.
  • Using Effects for derived values: Values that can be calculated directly from props or state usually do not need an Effect.

13. Best Practices for Dependency Arrays

  • Include all reactive values used by the Effect setup and cleanup.
  • Follow the React Hooks dependency lint rules.
  • Prefer primitive dependencies when they accurately describe what the Effect needs.
  • Move object or function creation inside the Effect when appropriate to avoid unstable references.
  • Use useCallback() or useMemo() only when memoization is genuinely useful, not as a default fix for every dependency issue.
  • Return cleanup functions for timers, subscriptions, and event listeners.
  • Use functional state updates when the next state depends on the previous state.
  • Avoid unnecessary Effects when the same result can be calculated during rendering.
  • Test components under React Strict Mode to identify cleanup problems.

14. Practical Example: Effect Dependency Demonstration

import { useEffect, useState } from "react";
function DependencyDemo() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState("React");
  useEffect(() => {
    console.log("Count or name changed:", count, name);
    return () => {
      console.log("Cleaning up previous Effect");
    };
  }, [count, name]);
  return (
    <div>
      <h1>Effect Dependency Demo</h1>
      <p>Count: {count}</p>
      <p>Name: {name}</p>
      <button onClick={() => setCount(previous => previous + 1)}>
        Increase Count
      </button>
      <button onClick={() => setName("React JS")}>
        Change Name
      </button>
    </div>
  );
}
export default DependencyDemo;

Expected Behavior

  1. The Effect runs after the initial commit.
  2. Clicking Increase Count changes count and triggers another Effect execution.
  3. Clicking Change Name changes name and triggers another Effect execution.
  4. Before the next setup, React runs the cleanup from the previous Effect.
  5. When the component unmounts, React runs the final cleanup.

15. Interview Questions and Answers

Q1. What is a dependency array in React?

A dependency array is the second argument to useEffect(). It identifies the reactive values that determine when the Effect needs to re-run.

Q2. What happens if the dependency array is omitted?

The Effect runs after every committed render of the component.

Q3. What does an empty dependency array mean?

The Effect runs after the initial client-side commit and does not re-run due to ordinary state or prop changes alone.

Q4. When does an Effect with dependencies run again?

It runs again after a commit when at least one dependency differs from its previous value according to Object.is().

Q5. Why should dependencies not be omitted?

Omitting required dependencies can cause an Effect to use outdated props or state and may create bugs.

Q6. Can a dependency array contain multiple values?

Yes. An Effect can depend on multiple props, state values, or other reactive values.

Q7. How does React compare dependency values?

React compares each dependency with its previous value using Object.is().

Q8. What is the purpose of Effect cleanup?

Cleanup releases resources, removes subscriptions, cancels unfinished work, or reverses the previous setup before the Effect runs again or the component unmounts.

16. Quick Revision Checklist

  • Understand the syntax of useEffect().
  • Know the difference between omitted, empty, and populated dependency arrays.
  • Understand how React compares dependencies.
  • Practice using state and props as dependencies.
  • Learn how dependency arrays control API synchronization.
  • Understand cleanup execution when dependencies change.
  • Avoid missing dependencies and infinite loops.
  • Know when an Effect is unnecessary.

17. Conclusion

Effect dependency arrays are essential for controlling when React Effects execute. An omitted dependency array causes execution after every committed render, an empty array prevents ordinary prop and state changes from triggering re-execution, and a populated array causes re-execution when a dependency changes. By specifying dependencies correctly and writing suitable cleanup logic, developers can build predictable, efficient, and maintainable React applications.


Learn React JS with JustAcademy

Strengthen your knowledge of React Hooks, component lifecycle, state management, and practical application development through structured training.

Explore JustAcademy React JS Training Course

Register for a React JS Course Demo

Previous Next
whatsapp