| Share Logic Between React Components :👈 | 👉:Why Should Not Call Hooks Conditionally |
How to Understand Hook Dependency Arrays |
How to Understand Hook Dependency Arrays in React
1. What Is a Dependency Array?
A dependency array is an array of values passed as the second argument to React Hooks such as useEffect, useMemo, and useCallback.
React uses the dependency array to determine whether an Effect needs to run again or whether a memoized value or function can be reused.
For example:
useEffect(() => {
console.log("Effect executed");
}, [count]);
Here, count is a dependency. React compares its value with the value from the previous render. If it changes, React runs the Effect again after the render has been committed.
2. The Three Common Dependency Array Patterns
Pattern 1: No Dependency Array
useEffect(() => {
console.log("Effect executed");
});
Behavior: React runs the Effect after every committed render.
Use this pattern only when the Effect genuinely needs to run after every render. Otherwise, specify dependencies to avoid unnecessary work.
Pattern 2: Empty Dependency Array
useEffect(() => {
console.log("Effect executed");
}, []);
Behavior: The Effect runs after the initial mount. Its cleanup runs when the component unmounts, if a cleanup function is returned.
However, an empty array does not mean the Effect runs exactly once in every development environment. React Strict Mode can run an extra setup-and-cleanup cycle in development to help identify bugs.
Important: An empty array is appropriate only when the Effect does not need to react to changing props or state. It is not a way to force an Effect to ignore values it uses.
Pattern 3: Dependency Array with Values
useEffect(() => {
console.log("Count changed:", count);
}, [count]);
Behavior: The Effect runs after the initial mount and again when count changes.
This is the most common pattern when an Effect depends on props, state, or other reactive values.
3. Quick Comparison
| Dependency Array | When the Effect Runs | Typical Use |
|---|---|---|
| Omitted | After every committed render | Effects that genuinely need every render |
[] |
After the initial mount, subject to development Strict Mode behavior | Setup that does not depend on changing reactive values |
[count] |
After the initial mount and when count changes |
Effects that depend on one value |
[count, userId] |
After the initial mount and when either dependency changes | Effects that depend on multiple values |
4. How Does React Check Dependencies?
React compares each dependency with its value from the previous render using Object.is.
If at least one dependency is different, React considers the dependencies changed.
Consider this example:
import { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Effect executed:", count);
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
export default Counter;
When the component first renders, count is 0, so the Effect runs after the initial commit.
When you click the button:
- The state changes from
0to1. - React renders the component again.
- React compares the new dependency value,
1, with the previous value,0. - Because the values differ, React runs the Effect after the commit.
If the dependency value remains unchanged, React does not rerun the Effect merely because the component rendered again.
5. What Should Be Included in a Dependency Array?
For useEffect, include the reactive values used by the Effect's setup code and cleanup code. These commonly include:
- Props used by the Effect.
- State variables used by the Effect.
- Variables and functions declared inside the component and used by the Effect.
- Values returned by other Hooks that can change between renders.
Consider this example:
import { useEffect } from "react";
function UserProfile({ userId }) {
useEffect(() => {
console.log("Loading user:", userId);
}, [userId]);
return <p>User ID: {userId}</p>;
}
The Effect uses userId, so userId belongs in the dependency array. When the parent passes a different user ID, the Effect runs again.
Rule of thumb: Do not guess which dependencies React needs. Include the reactive values the Effect actually reads, and use the React Hooks lint rules to identify missing dependencies.
6. What Happens When You Miss a Dependency?
Missing dependencies can cause an Effect to use outdated values. This is commonly called a stale closure.
Consider this incorrect example:
import { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
console.log(count);
}, 1000);
return () => clearInterval(timer);
}, []);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
The Effect captures the initial value of count, which is 0. Because the dependency array is empty, the interval continues to log that captured value even after the displayed count changes.
Solution 1: Include the Dependency
useEffect(() => {
const timer = setInterval(() => {
console.log(count);
}, 1000);
return () => clearInterval(timer);
}, [count]);
Now, whenever count changes, React cleans up the previous interval and creates a new one that captures the current value.
Solution 2: Use a Functional State Update
If the goal is to update state periodically, a functional update can avoid reading the previous state value from the Effect's closure.
import { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(previousCount => previousCount + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <p>Count: {count}</p>;
}
Here, the Effect does not read count. Instead, React passes the latest state value to the updater function. The interval can therefore remain active without depending on count.
7. Why Do Objects and Arrays Cause Dependency Problems?
Objects and arrays can cause unexpected Effect executions because JavaScript creates a new reference when a new object or array is constructed.
Consider this example:
import { useEffect } from "react";
function UserProfile({ userId }) {
const options = {
userId: userId,
includePosts: true
};
useEffect(() => {
console.log("Loading user data:", options);
}, [options]);
return <p>User ID: {userId}</p>;
}
Every render creates a new options object. Even if its properties are unchanged, its reference is different. React therefore considers the dependency changed and reruns the Effect.
Recommended Solution: Create the Object Inside the Effect
import { useEffect } from "react";
function UserProfile({ userId }) {
useEffect(() => {
const options = {
userId: userId,
includePosts: true
};
console.log("Loading user data:", options);
}, [userId]);
return <p>User ID: {userId}</p>;
}
This is usually the simplest solution when the object is needed only inside the Effect. The Effect now depends on the actual reactive value, userId.
The same principle applies to arrays and functions created during rendering: their references can change even when their contents or behavior appear equivalent.
8. How Do Dependency Arrays Work with useMemo?
useMemo caches the result of a calculation between renders while its dependencies remain unchanged.
import { useMemo, useState } from "react";
function ProductList({ products }) {
const [search, setSearch] = useState("");
const filteredProducts = useMemo(() => {
console.log("Filtering products");
return products.filter(product =>
product.name.toLowerCase().includes(search.toLowerCase())
);
}, [products, search]);
return (
<>
<input
value={search}
onChange={event => setSearch(event.target.value)}
placeholder="Search products"
/>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</>
);
}
The calculation uses both products and search, so both are dependencies.
- If
searchchanges, React recalculates the filtered list. - If the
productsreference changes, React recalculates the filtered list. - If neither dependency changes, React can reuse the previously calculated result.
Important: useMemo is a performance optimization, not a correctness guarantee. Your code must remain correct even if React recalculates the value.
9. How Do Dependency Arrays Work with useCallback?
useCallback caches a function reference between renders while its dependencies remain unchanged.
import { useCallback, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const showCount = useCallback(() => {
console.log("Current count:", count);
}, [count]);
return (
<>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={showCount}>
Show Count
</button>
</>
);
}
The function reads count, so count must be included in its dependency array.
When count changes, React returns a new function that captures the updated value. When count remains unchanged, React can reuse the previous function reference.
Remember:
useEffectuses dependencies to determine when an Effect must be resynchronized.useMemouses dependencies to determine when to recalculate a value.useCallbackuses dependencies to determine when to return a new function reference.
10. Common Dependency Array Mistakes
Mistake 1: Using an Empty Array to Avoid Reruns
useEffect(() => {
fetchUser(userId);
}, []);
If userId changes, this Effect will not automatically rerun to load the new user. It also captures the initial value of userId.
Correct approach:
useEffect(() => {
fetchUser(userId);
}, [userId]);
This assumes fetchUser is a stable function defined outside the component or otherwise does not need to be included as a changing dependency. If it is declared inside the component, include it as a dependency or restructure the code appropriately.
Mistake 2: Including Every Value Without Understanding Why
Do not add unrelated values to a dependency array. Include the reactive values the Hook actually uses. Extra dependencies can cause unnecessary recalculations or Effect reruns, particularly when their references change on every render.
Mistake 3: Omitting a Function Dependency
function Search({ query }) {
const searchProducts = () => {
console.log("Searching:", query);
};
useEffect(() => {
searchProducts();
}, [query]);
return null;
}
In this example, searchProducts is declared inside the component and is recreated on every render. The Effect uses that function, but the dependency array omits it.
The Hooks linter will warn about the missing dependency. A simple fix is to move the function's logic into the Effect:
function Search({ query }) {
useEffect(() => {
console.log("Searching:", query);
}, [query]);
return null;
}
If the function must be shared elsewhere, consider defining it outside the component when it does not need component-specific values, or use useCallback when memoizing the function reference is useful. Include all relevant dependencies in either case.
Mistake 4: Expecting Objects to Compare by Their Contents
const settings = { theme: "dark" };
useEffect(() => {
console.log("Settings changed");
}, [settings]);
If this object is created inside a component, its reference normally changes on each render. React compares the reference rather than deeply comparing the object's properties.
Prefer depending on the specific primitive values the Effect needs or constructing the object inside the Effect.
Mistake 5: Treating Dependency Arrays as a Scheduling Tool
Dependency arrays describe which reactive values an Effect depends on. They should not be used merely to control how often code runs. First identify what the Effect synchronizes with, then declare the values it reads.
11. How to Avoid Unnecessary Effect Executions
- Move objects and functions inside the Effect if they are used only there.
- Move functions that do not depend on component values outside the component when appropriate.
- Use functional state updates when the next state depends on the previous state.
- Use
useMemooruseCallbackwhen stable references provide a meaningful performance benefit. - Avoid using an Effect to calculate values that can be derived directly during rendering.
- Use the React Hooks lint rules to detect missing dependencies and other Hook mistakes.
Do not use memoization simply to silence a dependency warning. First check whether the code can be structured more simply.
12. When Should You Use an Effect at All?
Not every piece of logic belongs in useEffect.
Effects are primarily for synchronizing React components with external systems, such as:
- Network connections and subscriptions.
- Browser event listeners.
- Timers.
- Third-party widgets.
- Browser APIs that need synchronization after rendering.
If a value can be calculated directly from props or state, calculate it during rendering instead of storing a duplicate value and updating it through an Effect.
For example, avoid this unnecessary pattern:
const [firstName, setFirstName] = useState("Sam");
const [lastName, setLastName] = useState("Taylor");
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " " + lastName);
}, [firstName, lastName]);
Prefer deriving the value directly:
const [firstName, setFirstName] = useState("Sam");
const [lastName, setLastName] = useState("Taylor");
const fullName = firstName + " " + lastName;
This avoids an unnecessary Effect and an additional render caused by updating the derived state.
13. Special Cases: Values That Usually Do Not Belong in Dependencies
Some values do not behave like ordinary reactive values:
- State setter functions: Functions returned by
useState, such assetCount, have stable identities and generally do not need to be included as dependencies. - Reducer dispatch functions: The
dispatchfunction returned byuseReducerhas a stable identity and generally does not need to be included. - Ref objects: The object returned by
useRefhas a stable identity. Changes toref.currentdo not trigger a render, so React cannot use those changes to trigger an Effect through a dependency array. - Module-level constants: Values declared outside the component that do not change during rendering are not reactive dependencies.
When in doubt, follow the Hooks linter's guidance and understand whether the value can change between renders.
14. Quick Decision Guide
| Requirement | Approach |
|---|---|
| Run an Effect when a prop changes | Include the prop in the dependency array. |
| Run an Effect when a state value changes | Include the state value in the dependency array. |
| Recalculate an expensive value when inputs change | Consider useMemo with those inputs as dependencies. |
| Keep a function reference stable when useful | Consider useCallback with the values the function reads. |
| Use an object only inside an Effect | Usually create the object inside the Effect. |
| Update state based on its previous value | Consider a functional state update. |
| Calculate a value from existing props or state | Usually derive it during rendering instead of using an Effect. |
15. Best Practices
- Include every reactive value read by an Effect, memoized calculation, or callback.
- Do not suppress dependency warnings without understanding the underlying issue.
- Remember that React compares dependencies using
Object.is, not deep object comparison. - Use functional state updates when appropriate to avoid reading state values unnecessarily.
- Move Effect-only functions and objects inside the Effect when that simplifies dependencies.
- Use
useMemoanduseCallbackfor useful performance optimizations, not automatically everywhere. - Remember that Effects can run an extra setup-and-cleanup cycle in development Strict Mode.
- Make Effects safe to clean up and restart.
- Prefer derived values over Effects that synchronize redundant state.
- Use the
eslint-plugin-react-hooksrules to help detect missing dependencies.
16. React Hook Dependency Array Interview Questions
Q1. What is a dependency array?
A dependency array lists the reactive values that a Hook depends on. React compares those values with their previous values to determine whether an Effect should resynchronize or a memoized value or callback should be recalculated or recreated.
Q2. What happens if you omit the dependency array in useEffect?
The Effect runs after every committed render.
Q3. What does an empty dependency array mean?
It means the Effect does not declare changing reactive dependencies. It normally runs after the initial mount, with an extra setup-and-cleanup cycle possible in development Strict Mode.
Q4. What happens if you forget a dependency?
The Hook may continue using a value captured from an earlier render, resulting in a stale closure or incorrect behavior.
Q5. How does React compare dependencies?
React compares each dependency with its previous value using Object.is.
Q6. Why can an object dependency cause an Effect to run repeatedly?
If a new object is created during every render, its reference changes. React treats it as a changed dependency even if its properties contain the same values.
Q7. What is the difference between useMemo and useCallback?
useMemo caches a calculated value, while useCallback caches a function reference. Both use dependency arrays to determine when their cached results can be reused.
Q8. Should every state variable be included in every dependency array?
No. Include reactive values that the Hook actually reads. A state variable that the Hook does not use is not a dependency of that Hook.
Q9. Can useRef values trigger an Effect through a dependency array?
Changes to ref.current do not trigger a render. Therefore, React does not automatically rerun an Effect when only that property changes.
Q10. How can unnecessary Effect executions be reduced?
Remove unnecessary Effects, derive values during rendering, move Effect-only objects and functions inside the Effect, use functional state updates where appropriate, and apply memoization when it provides a real benefit.
17. Final Summary
useEffect(() => { ... })runs after every committed render.useEffect(() => { ... }, [])runs after the initial mount, subject to development Strict Mode behavior.useEffect(() => { ... }, [value])runs after the initial mount and whenvaluechanges.- React compares dependencies using
Object.is. - Missing dependencies can cause stale closures and incorrect behavior.
- Objects and functions created during rendering can change references on every render.
useEffectsynchronizes with external systems,useMemocaches calculated values, anduseCallbackcaches function references.- Dependency arrays should describe the values a Hook uses, not serve as a mechanism for forcing a preferred execution schedule.
The most important rule: First understand which reactive values your Hook uses. Then declare those dependencies correctly and restructure the code if you need to simplify the dependency list.
| Share Logic Between React Components :👈 | 👉:Why Should Not Call Hooks Conditionally |
Comments and Discussion