0
0
ReactHow-ToBeginner · 3 min read

How to Run useEffect on Specific State Change in React

To run useEffect only when a specific state changes, pass that state variable inside the dependency array as the second argument to useEffect. This tells React to run the effect only when that particular state updates.
📐

Syntax

The useEffect hook takes two arguments: a function to run (the effect) and an optional dependency array. The dependency array lists variables that the effect depends on. React runs the effect only when one of these variables changes.

Example parts:

  • useEffect(() => { ... }, [dependency]): effect runs when dependency changes.
  • If the array is empty [], effect runs only once after the first render.
  • If no array is provided, effect runs after every render.
javascript
useEffect(() => {
  // code to run
}, [specificState]);
💻

Example

This example shows a counter with two states: count and name. The useEffect runs only when count changes, not when name changes.

javascript
import React, { useState, useEffect } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');

  useEffect(() => {
    console.log('Count changed:', count);
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase Count</button>
      <p>
        Name: <input value={name} onChange={e => setName(e.target.value)} />
      </p>
    </div>
  );
}
Output
When you click 'Increase Count', console logs 'Count changed: X'. Changing the name input does not trigger the effect.
⚠️

Common Pitfalls

Common mistakes include:

  • Not including the specific state in the dependency array, so the effect does not run when expected.
  • Leaving the dependency array empty or missing, causing the effect to run too often or only once.
  • Including too many dependencies, causing unnecessary runs.

Always list exactly the states or props that should trigger the effect.

javascript
/* Wrong: effect does not run when 'count' changes because dependency array is empty */
useEffect(() => {
  console.log('Count changed:', count);
}, []);

/* Right: effect runs when 'count' changes */
useEffect(() => {
  console.log('Count changed:', count);
}, [count]);
📊

Quick Reference

  • Dependency array: List states/props that trigger effect.
  • Empty array []: Run effect once after first render.
  • No array: Run effect after every render.
  • Specific state: Put that state in array to run effect only on its change.

Key Takeaways

Put the specific state variable in useEffect's dependency array to run effect on its change.
An empty dependency array runs the effect only once after the first render.
Omitting the dependency array runs the effect after every render, which can hurt performance.
Avoid including unnecessary dependencies to prevent extra effect runs.
Always keep the dependency array accurate to control when effects run.