The dependency array tells React when to run some code again. It helps avoid running code too many times or missing updates.
Dependency array usage in React
useEffect(() => {
// code to run
}, [dependency1, dependency2]);The array at the end is called the dependency array.
React runs the code inside useEffect only if one of the dependencies changes.
useEffect(() => {
console.log('Runs once when component mounts');
}, []);count value changes.useEffect(() => {
console.log('Runs when count changes:', count);
}, [count]);useEffect(() => {
console.log('Runs every render because no array');
});user or theme changes.useEffect(() => {
console.log('Runs when user or theme changes');
}, [user, theme]);This component shows how dependency arrays control when effects run:
- The first effect runs only once when the component appears.
- The second effect runs only when
countchanges. - The third effect runs only when
namechanges.
Try clicking the button or typing in the input to see console logs.
import React, { useState, useEffect } from 'react'; function Counter() { const [count, setCount] = useState(0); const [name, setName] = useState(''); useEffect(() => { console.log('Component mounted'); }, []); useEffect(() => { console.log(`Count changed to: ${count}`); }, [count]); useEffect(() => { console.log(`Name changed to: ${name}`); }, [name]); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increase Count</button> <p>Name: {name}</p> <input type="text" value={name} onChange={e => setName(e.target.value)} aria-label="Name input" /> </div> ); } export default Counter;
Time complexity: Effects run only when dependencies change, so efficient updates.
Space complexity: Minimal, just stores dependencies internally.
Common mistake: Forgetting to add dependencies causes effects to not update when expected.
Use dependency arrays to control when side effects run and avoid unnecessary work.
The dependency array controls when React runs your effect code.
Empty array means run once; no array means run every render.
Always list all variables your effect uses in the dependency array.
Practice
[] in a useEffect hook mean?Solution
Step 1: Understand the role of dependency array
The dependency array tells React when to run the effect based on changes in listed variables.Step 2: Interpret empty array meaning
An empty array means no variables to watch, so React runs the effect only once after the first render.Final Answer:
The effect runs only once after the first render. -> Option DQuick Check:
Empty array = run once [OK]
- Thinking empty array runs effect every render
- Confusing empty array with no array
- Assuming effect never runs with empty array
useEffect hook that runs only once after the component mounts?Solution
Step 1: Identify correct useEffect syntax
The second argument is the dependency array controlling when the effect runs.Step 2: Check which option uses empty array
useEffect(() => { console.log('Hello'); }, []); uses an empty array, so effect runs once after mount, which is correct.Final Answer:
useEffect(() => { console.log('Hello'); }, []); -> Option BQuick Check:
Empty array syntax = useEffect(() => { console.log('Hello'); }, []); [OK]
- Omitting dependency array runs effect every render
- Using non-constant values in dependency array incorrectly
- Confusing dependency array with effect callback
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count is', count);
}, [count]);
setCount(1);
setCount(2);What will be logged to the console?
Solution
Step 1: Understand effect dependency on count
The effect runs after first render (count=0) and whenever count changes.Step 2: Analyze state updates
Two state updates happen quickly: setCount(1) then setCount(2). React batches them, so only final count=2 triggers effect after initial render.Final Answer:
Count is 0, Count is 2 -> Option AQuick Check:
Effect runs on initial and final count change [OK]
- Assuming effect runs for every intermediate state update
- Ignoring batching of state updates
- Thinking effect runs before first render
useEffect usage?const [count, setCount] = useState(0);
useEffect(() => {
console.log(count);
}, []);Solution
Step 1: Check dependency array usage
Empty array means effect runs once after first render only.Step 2: Understand effect behavior with state
Effect logs count only once with initial value, ignoring later count changes.Final Answer:
Effect will run only once and log initial count, ignoring updates. -> Option AQuick Check:
Empty array ignores state changes [OK]
- Thinking effect runs on every count change
- Assuming empty array stops effect from running
- Confusing syntax error with logical error
useEffect that depends on two props: userId and filter. Which dependency array is correct to ensure the effect runs only when these props change?useEffect(() => {
fetchData(userId, filter);
}, ???);Solution
Step 1: Identify variables used inside effect
The effect usesuserIdandfilterinside its callback.Step 2: List all used variables in dependency array
To rerun effect when eitheruserIdorfilterchanges, both must be in the dependency array.Final Answer:
[userId, filter] -> Option CQuick Check:
List all used variables in dependencies [OK]
- Leaving dependency array empty causing stale data
- Including functions that don't change as dependencies
- Listing only some used variables
Ready to prove it?
Pass the test and this pattern moves unknown
