0
0
Reactframework~5 mins

Dependency array usage in React

Choose your learning style9 modes available
Introduction

The dependency array tells React when to run some code again. It helps avoid running code too many times or missing updates.

When you want to run code only once when a component loads.
When you want to run code again only if some data changes.
When you want to avoid running code on every render to save time.
When you want to update something after a user changes a value.
When you want to fetch new data only if a filter or input changes.
Syntax
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.

Examples
Empty array means run only once when the component appears.
React
useEffect(() => {
  console.log('Runs once when component mounts');
}, []);
Runs only when the count value changes.
React
useEffect(() => {
  console.log('Runs when count changes:', count);
}, [count]);
No dependency array means run on every render (not recommended usually).
React
useEffect(() => {
  console.log('Runs every render because no array');
});
Runs when either user or theme changes.
React
useEffect(() => {
  console.log('Runs when user or theme changes');
}, [user, theme]);
Sample Program

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 count changes.
  • The third effect runs only when name changes.

Try clicking the button or typing in the input to see console logs.

React
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;
OutputSuccess
Important Notes

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.

Summary

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.