Popular Searches
Popular Course Categories
Popular Courses

Hook Dependencies

Hook Dependencies

React Hooks Fundamentals

Hook Dependencies in React JS – Complete Detailed Notes

Hook Dependencies are values that React Hooks use to determine when an Effect should run again, when a calculation should be recomputed, or when a function reference should be updated. Dependencies are commonly used with React Hooks such as useEffect, useMemo, and useCallback.

Learn more through JustAcademy React JS Training or Register for React JS Course Demo.


1. What Are Hook Dependencies?

Hook dependencies are values listed in an array passed to a Hook. React compares the current dependency values with the previous values to decide whether the Hook's associated work needs to be repeated.

Dependencies can include props, state values, and variables or functions declared inside a component that are used by the Hook callback.

Basic example

import { useEffect, useState } from 'react';

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

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

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

export default Counter;

Explanation: The dependency array contains count. The Effect runs after the initial commit and runs again after a commit when count changes.


2. Why Are Hook Dependencies Important?

Dependencies help React Hooks respond to changes in the values they use. Correct dependencies keep Effects synchronized with current props and state, help memoized calculations stay accurate, and prevent callbacks from using outdated values.

  • Correct behavior: Effects respond to relevant value changes.
  • Fresh data: Callbacks and Effects use the appropriate values from the current render.
  • Performance: Memoization can avoid repeating expensive calculations when dependencies remain unchanged.
  • Resource management: Effects can reconnect, resubscribe, or clean up when relevant values change.
  • Bug prevention: Correct dependencies help prevent stale closures and synchronization errors.

3. Understanding the Dependency Array

A dependency array is written using square brackets []. Its meaning depends on the Hook being used.

3.1 No dependency array

useEffect(() => {
  console.log('Effect ran after a commit');
});

When the dependency argument is omitted, the Effect runs after every committed render.

3.2 Empty dependency array

useEffect(() => {
  console.log('Effect setup');
}, []);

An empty array means the Effect has no reactive dependencies. Its setup runs after the initial commit, and its cleanup runs when the component is removed. In development Strict Mode, React may perform an additional setup-and-cleanup cycle.

3.3 Dependency array with values

useEffect(() => {
  console.log('Search term changed:', searchTerm);
}, [searchTerm]);

The Effect runs after the initial commit and again when searchTerm changes.

Comparison table

Syntax Effect Behavior Example Use
useEffect(fn) Runs after every commit. Rare cases where synchronization is needed after every commit.
useEffect(fn, []) Runs after the initial commit; cleanup runs on removal. Setting up an external resource with no reactive dependencies.
useEffect(fn, [count]) Runs after the initial commit and when count changes. Synchronizing with a changing count.
useEffect(fn, [a, b]) Runs when either dependency changes. Updating a connection when its URL or room changes.

4. What Values Should Be Included as Dependencies?

For an Effect, include every reactive value from the component that is read by the Effect's setup or cleanup logic. Reactive values commonly include props, state, and variables or functions declared inside the component.

Example

import { useEffect, useState } from 'react';

function Greeting({ username }) {
  const [language, setLanguage] = useState('English');

  useEffect(() => {
    console.log(`Hello ${username}, language: ${language}`);
  }, [username, language]);

  return (
    <button onClick={() => setLanguage('Hindi')}>
      Change Language
    </button>
  );
}

export default Greeting;

Both username and language are read inside the Effect, so both are listed as dependencies. When either value changes, the Effect runs again after the corresponding commit.

Common dependency types

Dependency Type Example
Props [userId]
State [count]
Multiple values [firstName, lastName]
Function declared in a component [handleUpdate], if the Effect uses it and its identity can change.
Object declared in a component [options], if the Effect uses it; a new object on every render may cause repeated execution.

5. How React Compares Dependencies

React compares each dependency with its previous value using Object.is. If at least one dependency is different, React treats the dependency list as changed.

Example with a number

useEffect(() => {
  console.log('Count is now:', count);
}, [count]);

If count changes from 2 to 3, the dependency has changed and the Effect runs after the commit. If count remains 3, the dependency has not changed, so the Effect does not run again solely because of this dependency.

Example with an object

const user = { name: 'Manish' };

useEffect(() => {
  console.log(user.name);
}, [user]);

If this object is created inside a component, a new object reference is created on each render. React therefore treats user as changed even when its properties look identical.

Important: For objects and arrays, React compares references rather than deeply comparing every property.


6. Hook Dependencies With useEffect

The useEffect Hook is used to synchronize a component with external systems, such as network requests, browser APIs, subscriptions, and timers. Its dependency list controls when React repeats the synchronization.

Example: Update Browser Tab Title

import { useEffect, useState } from 'react';

function PageTitle() {
  const [title, setTitle] = useState('Home');

  useEffect(() => {
    document.title = title;
  }, [title]);

  return (
    <div>
      <h2>Current Page: {title}</h2>
      <button onClick={() => setTitle('Dashboard')}>
        Open Dashboard
      </button>
    </div>
  );
}

export default PageTitle;

How it works

  1. The component starts with the title Home.
  2. React renders the component.
  3. The Effect updates the browser tab title.
  4. When the button is clicked, title changes to Dashboard.
  5. React renders again and the Effect synchronizes the browser title with the new value.

7. Hook Dependencies With useMemo

The useMemo Hook caches the result of a calculation between renders. React recalculates the value when one or more dependencies change.

Syntax

const memoizedValue = useMemo(() => {
  return calculateValue(a, b);
}, [a, b]);

Example: Calculate a Total

import { useMemo, useState } from 'react';

function PriceCalculator() {
  const [price, setPrice] = useState(100);
  const [quantity, setQuantity] = useState(2);
  const [theme, setTheme] = useState('light');

  const total = useMemo(() => {
    console.log('Calculating total');
    return price * quantity;
  }, [price, quantity]);

  return (
    <div className={`page-${theme}`}>
      <p>Price: {price}</p>
      <p>Quantity: {quantity}</p>
      <h2>Total: {total}</h2>
      <button onClick={() => setPrice(value => value + 10)}>
        Increase Price
      </button>
      <button onClick={() => setQuantity(value => value + 1)}>
        Increase Quantity
      </button>
      <button onClick={() => setTheme(value => value === 'light' ? 'dark' : 'light')}>
        Toggle Theme
      </button>
    </div>
  );
}

export default PriceCalculator;

The total is recalculated when price or quantity changes. Changing the theme alone does not invalidate the memoized calculation because theme is not one of its dependencies.

Note: For simple calculations such as price multiplied by quantity, useMemo may not be necessary. It is primarily a performance optimization for expensive calculations or values that need stable references.


8. Hook Dependencies With useCallback

The useCallback Hook caches a function definition between renders. React returns the same function reference while its dependencies remain unchanged.

Syntax

const handleClick = useCallback(() => {
  doSomething(value);
}, [value]);

Example

import { useCallback, useState } from 'react';

function SearchButton() {
  const [query, setQuery] = useState('');

  const handleSearch = useCallback(() => {
    console.log('Searching for:', query);
  }, [query]);

  return (
    <div>
      <input
        value={query}
        onChange={event => setQuery(event.target.value)}
        placeholder="Enter search term"
      />
      <button onClick={handleSearch}>Search</button>
    </div>
  );
}

export default SearchButton;

The callback uses query, so query is included in the dependency array. When query changes, React returns a new callback that captures the latest query value.

Remember: useCallback memoizes a function reference, while useMemo memoizes the result of a calculation.


9. Missing Dependencies and Stale Closures

A stale closure occurs when a callback or Effect continues to use values captured from an earlier render instead of the values you expect it to use.

Incorrect example

import { useEffect, useState } from 'react';

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

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

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

The Effect has an empty dependency array even though it reads count. It therefore does not run again when count changes and continues to represent the initial value in its setup closure.

Correct example

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

Now the Effect responds to changes in count.

Important: Do not remove a required dependency just to make an Effect run less often. Instead, restructure the code so that the Effect genuinely depends only on the values it needs.


10. Unnecessary Dependencies

Sometimes a dependency causes an Effect to run more often than necessary. A common reason is creating an object or function during rendering and then using it as a dependency.

Problem: Object created during render

function ChatRoom({ roomId }) {
  const options = {
    serverUrl: 'https://example.com',
    roomId
  };

  useEffect(() => {
    const connection = createConnection(options);
    connection.connect();

    return () => connection.disconnect();
  }, [options]);

  return <p>Room: {roomId}</p>;
}

Every render creates a new options object. Since the reference changes, the Effect can reconnect unnecessarily after every render.

Better approach: Create the object inside the Effect

function ChatRoom({ roomId }) {
  useEffect(() => {
    const options = {
      serverUrl: 'https://example.com',
      roomId
    };

    const connection = createConnection(options);
    connection.connect();

    return () => connection.disconnect();
  }, [roomId]);

  return <p>Room: {roomId}</p>;
}

Now the Effect depends on roomId, the reactive value that determines which room to connect to. The example assumes createConnection is defined or imported elsewhere.


11. Dependency Arrays and Cleanup Functions

When an Effect returns a cleanup function, React runs that cleanup before running the Effect again with changed dependencies and when the component is removed.

Example: Subscribe to a Selected Room

import { useEffect } from 'react';

function ChatRoom({ roomId }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();

    return () => {
      connection.disconnect();
    };
  }, [roomId]);

  return <p>Connected to room: {roomId}</p>;
}

Execution sequence

  1. The component appears and React connects to the initial room.
  2. The roomId prop changes.
  3. React runs cleanup for the previous connection.
  4. React establishes a new connection using the new roomId.
  5. When the component is removed, React disconnects the final connection.

This pattern is useful for subscriptions, timers, WebSocket connections, and event listeners that depend on changing values.


12. Dependency Arrays With Multiple Values

A Hook can depend on more than one value. Every reactive value used by the callback should be included in the dependency array.

useEffect(() => {
  console.log('User:', userId);
  console.log('Page:', pageNumber);
  console.log('Filter:', filter);
}, [userId, pageNumber, filter]);

The Effect runs after the initial commit and again after a commit when userId, pageNumber, or filter changes.

Dependencies should be written inline, and the number and order of entries should remain constant between renders.


13. Dependency Arrays With Arrays and Objects

React does not deeply compare the contents of arrays or objects when checking Hook dependencies. It compares their references using Object.is.

Example of a new array on each render

function ProductList({ products }) {
  const filters = ['available', 'featured'];

  useEffect(() => {
    console.log('Applying filters:', filters);
  }, [filters]);

  return <p>Products: {products.length}</p>;
}

In this example, filters is recreated on every render, so the Effect sees a new dependency reference each time.

Better approach

function ProductList({ products }) {
  useEffect(() => {
    const filters = ['available', 'featured'];
    console.log('Applying filters:', filters);
  }, []);

  return <p>Products: {products.length}</p>;
}

Because the array is only needed inside the Effect and contains no reactive values, it can be created inside the Effect. If the array needs to change based on props or state, include those reactive values instead.


14. Dependency Arrays and Event Handlers

Event handlers and Effects have different purposes. Event handlers run in response to specific user interactions, while Effects synchronize with external systems based on the component's current values.

function SearchForm() {
  const [query, setQuery] = useState('');

  function handleSubmit(event) {
    event.preventDefault();
    console.log('Search requested:', query);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={query}
        onChange={event => setQuery(event.target.value)}
      />
      <button type="submit">Search</button>
    </form>
  );
}

The search action belongs in the submit handler because it should happen when the user submits the form. An Effect is not needed merely to respond to that click or submission.


15. Rules for Hook Dependencies

  • Include all reactive values used by an Effect, memoized calculation, or callback.
  • Do not add unrelated values simply because they exist in the component.
  • Do not omit dependencies to silence lint warnings.
  • Keep dependency arrays inline and constant in length and order.
  • Understand that React compares dependencies using Object.is.
  • Move objects and functions inside an Effect when they are only needed there and doing so simplifies dependencies.
  • Use useMemo or useCallback when stable references provide a real benefit.
  • Remember that memoization is an optimization, not a replacement for correct dependencies.
  • Use state for values that affect the UI and Effects for synchronization with external systems.
  • Call Hooks at the top level of function components or custom Hooks, not inside conditions or loops.

16. Common Hook Dependency Mistakes

Mistake Problem Solution
Missing a state dependency The Effect can use an outdated value. Include the state value in the dependency array.
Missing a prop dependency The Effect may not synchronize when the prop changes. Include the prop when it is used by the Effect.
Using no dependency array accidentally The Effect runs after every commit. Add the correct dependency array when appropriate.
Using an empty array with reactive values The Effect does not respond to those values changing. Include the reactive values or restructure the logic.
Using a newly created object as a dependency The Effect may run on every render. Create the object inside the Effect or stabilize it if necessary.
Using useMemo without dependencies The calculation runs on every render. Supply the correct dependency array.
Using useCallback with missing dependencies The callback can capture stale values. Include the reactive values the callback uses.
Suppressing dependency lint rules Potential synchronization bugs may be hidden. Restructure the code and follow the dependency rules.

17. Practical Project: Search Filter With Hook Dependencies

Create a product list with a search field. The list should update when the search query changes.

import { useMemo, useState } from 'react';

const products = [
  'Laptop',
  'Mobile Phone',
  'Headphones',
  'Keyboard',
  'Mouse',
  'Monitor'
];

function ProductSearch() {
  const [query, setQuery] = useState('');

  const filteredProducts = useMemo(() => {
    const normalizedQuery = query.toLowerCase().trim();

    return products.filter(product =>
      product.toLowerCase().includes(normalizedQuery)
    );
  }, [query]);

  return (
    <div>
      <h2>Product Search</h2>
      <input
        type="text"
        value={query}
        onChange={event => setQuery(event.target.value)}
        placeholder="Search products..."
      />
      <ul>
        {filteredProducts.map(product => (
          <li key={product}>{product}</li>
        ))}
      </ul>
    </div>
  );
}

export default ProductSearch;

Project explanation

  • The query state stores the text entered by the user.
  • useMemo calculates the filtered list based on query.
  • The dependency array contains query because the calculation reads it.
  • When query changes, React recalculates the filtered list.
  • When query remains unchanged, React can reuse the memoized result.

For a small list, useMemo may not be needed. This project demonstrates dependency behavior; memoization becomes more useful when the calculation is expensive.


18. Interview Questions and Answers

Q1. What are Hook dependencies in React?

Answer: Hook dependencies are values listed in a dependency array that help React determine when to repeat an Effect, recalculate a memoized value, or update a memoized callback.

Q2. What is a dependency array?

Answer: A dependency array is a list of values passed to a Hook, such as useEffect, useMemo, or useCallback.

Q3. What happens when useEffect has no dependency array?

Answer: Its setup runs after every committed render.

Q4. What happens when useEffect has an empty dependency array?

Answer: Its setup runs after the initial commit, and cleanup runs when the component is removed. Development Strict Mode may run an additional setup-and-cleanup cycle.

Q5. How does React compare dependencies?

Answer: React compares each dependency with its previous value using Object.is.

Q6. What is a stale closure?

Answer: A stale closure occurs when a function continues to use values captured from an earlier render instead of the latest values expected by the logic.

Q7. Why can an object dependency cause repeated Effects?

Answer: A newly created object has a new reference, even when its properties are identical. React treats that reference as changed.

Q8. What is the difference between useMemo and useCallback?

Answer: useMemo caches the result of a calculation, while useCallback caches a function reference.

Q9. Should we remove dependencies to improve performance?

Answer: No. Required dependencies should not be removed. Restructure the code or use appropriate optimizations to avoid unnecessary work.

Q10. Do all Hooks use dependency arrays?

Answer: No. Some Hooks, such as useEffect, useMemo, and useCallback, accept dependency arrays, while many other Hooks do not.

Q11. What does the exhaustive-deps lint rule do?

Answer: It checks whether dependency lists include reactive values used by Hooks and helps identify missing dependencies.

Q12. When should useMemo be used?

Answer: It is useful when caching an expensive calculation or preserving a value's reference provides a meaningful performance benefit.


19. Practice Exercises

  1. Create a counter with an Effect that logs the latest count and includes the correct dependency.
  2. Create a search component that uses useMemo to filter a large list based on a query.
  3. Write a component that uses useCallback for a function that depends on a search term.
  4. Create an object dependency and observe why the Effect runs on each render.
  5. Refactor an Effect to create its options object inside the Effect instead of using it as a dependency.
  6. Build a timer that cleans up correctly when its duration or configuration changes.
  7. Identify a missing dependency and explain the stale value it can produce.
  8. Explain the difference between an omitted dependency array and an empty dependency array.

20. Quick Revision Checklist

  • Understand what Hook dependencies are.
  • Know the difference between no dependency array, an empty array, and an array containing values.
  • Include all reactive values used by the Hook callback.
  • Understand how React compares dependencies with Object.is.
  • Recognize stale closures caused by missing dependencies.
  • Know how object and function references can cause repeated Effects.
  • Understand dependency arrays in useEffect, useMemo, and useCallback.
  • Use cleanup functions for external resources.
  • Follow dependency lint warnings rather than suppressing them.
  • Use memoization only when it provides a real benefit.

21. Official React Documentation


22. Conclusion

Hook dependencies are essential for writing reliable React applications. They help Effects respond to relevant changes, keep memoized calculations accurate, and ensure callbacks use the appropriate values. Understanding dependency arrays, reference comparisons, cleanup functions, and stale closures helps prevent common React bugs.

Remember: Include the reactive values a Hook uses, avoid unnecessary object and function dependencies, and do not remove required dependencies just to stop repeated execution.

Continue learning through JustAcademy React JS Training and Register for React JS Course Demo.

Previous Next
whatsapp