🎓 A1Learner
🔍
0 of 50 lessons completed

Effects and Dependencies

Effects and dependencies control when an effect runs again. The dependency list names the values the effect watches.

Run when count changes

The effect watches count, so it runs after each click.

const [count, setCount] = useState(0);
const [message, setMessage] = useState('No clicks yet.');
useEffect(() => {
  setMessage('Count is ' + count + '.');
}, [count]);
return <p>{message}</p>;

Run once only

The empty list runs the effect only after mount.

const [count, setCount] = useState(0);
useEffect(() => {
  console.log('Mounted.');
}, []);
return <p>{count}</p>;

Example

import { useState, useEffect } from 'react';

export default function App() {
  const [count, setCount] = useState(0);
  const [message, setMessage] = useState('No clicks yet.');

  useEffect(() => {
    setMessage('Count is ' + count + '.');
  }, [count]);

  return (
    <div>
      <p>{message}</p>
      <button onClick={() => setCount(count + 1)}>Click</button>
    </div>
  );
}

Key points

  • The dependency list is the second argument of useEffect.
  • The effect runs after mount and after a watched value changes.
  • An empty list runs the effect only after mount.
  • A missing value in the list leaves the effect with old data.
  • Every value from outside the effect belongs in the list.

In this example, the count state value starts at zero. The message state value starts as No clicks yet. The effect watches count in its dependency list. The first render shows No clicks yet because the effect has not run yet. After mount, the effect sets the message to Count is 0. A click changes count, so the effect runs again.

Note

The list holds values, not the whole component.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When does an effect with [count] in its dependency list run again?