0
0
ReactConceptBeginner · 3 min read

What is Dependency Array in useEffect in React

The 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.

javascript
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;
Output
A button labeled 'Click me' and text showing 'You clicked 0 times'. Clicking the button increments the count and updates the browser tab title to 'Count: X' where X is the current count.
🎯

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 useEffect runs.
  • 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).
âś…

Key Takeaways

The dependency array tells React when to rerun the effect based on value changes.
Always list all variables your effect uses inside the dependency array.
An empty dependency array runs the effect only once when the component mounts.
Omitting the dependency array causes the effect to run after every render.
Using the dependency array properly improves app performance and correctness.