What is Dependency Array in useEffect in React
dependency array in React's useEffect hook is a list of values that tells React when to run the effect. React runs the effect only when one of these values changes, helping control when side effects happen.How It Works
Think of the useEffect hook as a reminder that runs some code after your component shows up on the screen or updates. The dependency array is like a list of things you watch closely. If any item on this list changes, React runs your reminder code again.
Imagine you have a plant and you only want to water it when the soil feels dry or the weather changes. The dependency array is like checking those conditions. If nothing changes, you don’t water the plant again. This saves effort and keeps your app efficient.
Example
This example shows a counter that updates the document title only when the count changes, thanks to the dependency array.
import React, { useState, useEffect } from 'react'; function Counter() { const [count, setCount] = useState(0); useEffect(() => { document.title = `Count: ${count}`; }, [count]); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } export default Counter;
When to Use
Use the dependency array whenever you want to control when your effect runs. It helps avoid running effects unnecessarily, which can slow down your app or cause bugs.
For example, if you fetch data from a server based on a user ID, include that ID in the dependency array. This way, the fetch runs only when the user ID changes, not on every render.
Leaving the array empty [] means the effect runs only once when the component first appears, like setting up a timer or subscribing to a service.
Key Points
- The dependency array controls when
useEffectruns. - Include all values your effect depends on to keep it updated correctly.
- An empty array runs the effect only once on mount.
- Omitting the array runs the effect after every render (usually not desired).