Introduction
The dependency array controls when a React useEffect needs to run again. By adding state variables, props, or other reactive values to the dependency array, React can re-synchronize the effect when those values change. Understanding dependencies is important for writing predictable React components and avoiding unnecessary effect executions. In this chapter, we will solve practical questions based on useEffect dependencies. React js useEffect with Dependencies practice questions with solutions help to understand the concepts.
1. What are Dependencies in useEffect?
Dependencies are values that an effect uses and needs to stay synchronized with.
They are provided inside the dependency array:
useEffect(() => {
console.log(count);
}, [count]);
Here, count is a dependency of the effect.
When count changes between commits, React runs the effect again.
2. Why is the Dependency Array used in useEffect?
The dependency array tells React which reactive values the effect depends on.
For example:
useEffect(() => {
console.log("Count changed:", count);
}, [count]);
The effect is synchronized when count changes.
Without dependencies:
useEffect(() => {
console.log("Effect executed");
});
The effect runs after every completed render/commit.
Using the appropriate dependencies makes the effect behavior more predictable and avoids unnecessary synchronization.
3. How do you use useEffect with a State Dependency?
You can add a state variable to the dependency array.
import { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Current count:", count);
}, [count]);
return (
<div>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
Whenever count changes, the effect runs again after the corresponding commit.
4. What is the difference between useEffect with no dependencies and with dependencies?
Consider these two examples.
Without a dependency array:
useEffect(() => {
console.log("Effect");
});
The effect runs after every completed render/commit.
With a dependency:
useEffect(() => {
console.log("Count changed");
}, [count]);
The effect runs after the initial commit and when count changes.
Therefore, the dependency array helps React determine when the effect needs to re-synchronize.
5. Can useEffect have multiple dependencies?
Yes. Multiple dependencies can be placed inside the dependency array.
useEffect(() => {
console.log("User information changed");
}, [name, age]);
Here, the effect depends on both name and age.
If either dependency changes, React runs the effect again after the corresponding commit.
Example:
function User({ name, age }) {
useEffect(() => {
console.log(name, age);
}, [name, age]);
return (
<div>
<h2>{name}</h2>
<p>{age}</p>
</div>
);
}
6. What happens when a dependency does not change?
React compares the dependency values from the previous committed render with the current ones.
If the dependencies have not changed, React does not re-run that effect because of those unchanged dependencies.
Example:
useEffect(() => {
console.log("Count effect");
}, [count]);
If another state variable changes but count remains the same, this particular effect does not need to re-run because of that other state change.
This helps prevent unnecessary effect execution.
7. How do you use a Prop as a useEffect Dependency?
Props can also be dependencies.
import { useEffect } from "react";
function User({ username }) {
useEffect(() => {
console.log("Username:", username);
}, [username]);
return <h2>{username}</h2>;
}
export default User;
When the parent provides a different username, the component receives the new prop and the effect re-synchronizes.
This is useful when an effect needs to respond to changing information received from a parent component.
8. How do you use multiple State Values as Dependencies?
Suppose a component has both search and category state values.
import { useEffect, useState } from "react";
function Products() {
const [search, setSearch] = useState("");
const [category, setCategory] = useState("all");
useEffect(() => {
console.log("Search:", search);
console.log("Category:", category);
}, [search, category]);
return (
<div>
<input
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Search products"
/>
<select
value={category}
onChange={(event) => setCategory(event.target.value)}
>
<option value="all">All</option>
<option value="laptop">Laptop</option>
<option value="mobile">Mobile</option>
</select>
</div>
);
}
export default Products;
The effect depends on both values.
Whenever search or category changes, the effect runs again.
9. How do you use a Dependency with API Data Fetching?
Dependencies are especially useful when data needs to be fetched based on a changing value.
For example, suppose users are loaded according to a selected user ID:
import { useEffect, useState } from "react";
function UserDetails({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
async function fetchUser() {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
);
const data = await response.json();
setUser(data);
}
fetchUser();
}, [userId]);
return (
<div>
{user ? (
<h2>{user.name}</h2>
) : (
<p>Loading...</p>
)}
</div>
);
}
export default UserDetails;
Here, userId is a dependency.
When userId changes, the effect runs again and requests the corresponding user data.
10. Build a Practical Search Component using useEffect Dependencies
Create a simple component where the effect responds to a changing search term.
import { useEffect, useState } from "react";
function SearchBox() {
const [search, setSearch] = useState("");
useEffect(() => {
if (search.trim() === "") {
console.log("Search is empty");
return;
}
console.log("Searching for:", search);
}, [search]);
return (
<div>
<h1>Product Search</h1>
<input
type="text"
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Search product"
/>
<p>Search Term: {search}</p>
</div>
);
}
export default SearchBox;
How it works:
searchis stored in state.- The input updates
searchthroughonChange. searchis included in the dependency array.- When
searchchanges, the effect runs. - The effect can then perform synchronization or another external operation based on the new search term.
This pattern is useful for search-related API requests, browser interactions, or other external synchronization. For real applications, you may also need techniques such as debouncing and request cancellation.
Key Takeaways
- The dependency array controls when an effect needs to re-synchronize.
- State values can be added as dependencies.
- Props can also be added as dependencies.
- Multiple dependencies can be provided in one dependency array.
- An effect with no dependency array runs after every completed render/commit.
- An effect with
[count]runs after the initial commit and whencountchanges. - React compares dependency values between commits to determine whether the effect should run again.
- Dependencies should reflect the reactive values used by the effect.
- Dependency-based effects are useful for API requests, search operations, browser APIs, and external synchronization.
useEffectshould not be used when a value can simply be calculated during rendering.
FAQs
1. What is a dependency in useEffect?
A dependency is a reactive value that an effect uses and needs to stay synchronized with.
2. How do I add a dependency to useEffect?
Add the value inside the dependency array:
useEffect(() => {
console.log(count);
}, [count]);
3. Can I add multiple dependencies to useEffect?
Yes. Multiple values can be added:
useEffect(() => {
console.log(name, age);
}, [name, age]);
4. What happens if a dependency changes?
React re-runs the effect after the corresponding commit when a dependency value has changed.
5. Can props be used as useEffect dependencies?
Yes. If an effect uses a prop and needs to respond to changes in that prop, the prop should generally be included in the dependency array.
6. What happens if I leave the dependency array empty?
An empty dependency array means the effect has no changing reactive dependencies. It normally runs after the initial mount.
7. Why is it important to use the correct dependencies?
Correct dependencies help the effect stay synchronized with the values it uses and reduce incorrect or unnecessary effect executions.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
