How does a useEffect know to listen to a state variable?

  const [selected, setSelected] = useState(1);
  
  useEffect(() => {}, [selected])

Since selected is just 1, why isn't the useEffect above equivalent to:

  useEffect(() => {}, [1])

Upvotes: 0

Views: 429

Answers (1)

buondevid
buondevid

Reputation: 726

Well, in the first example, when selected changes the effect re-runs. In your second example, you've put a hard-coded value in the deps array (that's never going to change), so the effect will never run again after the first component mount.

So to answer your question:

  • With example 1 you are saying: I expect this selected state to change at some point, when that happens re-run the effect.
  • With example 2 you are saying: the deps never change, don't re-run the effect. In this case, you should just leave the deps array empty, which has the same effect and it's cleaner.

Upvotes: 2

Related Questions