0
const [messageCount, setMessageCount] = useState(0)
const [username, setUsername] = useState('Andres')
...
useEffect(
  () => {
    console.log(`Hello ${name}, you have ${count} unread messages`)
  },
  [name, count]
)

In a scenario like the above, where the second argument of useEffect has more than one item, and they're basically values. How does it differentiate each item ?

if at a given time, name = 'Andres' and count = 10, and moments later count = 20

How does useEffect decide how to compare items:

'Andres' === 10 or 10 === 20 ?

Andres Zapata
  • 1,710
  • 1
  • 16
  • 32
  • The answer is simple, If one of the dependencies has changed since the last time, the effect will run again. what do you want to know exactly? – Mehdi Dehghani Jan 16 '20 at 05:18
  • @MehdiDehghani I'm not asking what but how. I tried looking at the source code but I couldn't figure it out. – Andres Zapata Jan 16 '20 at 05:19
  • It uses shallow equal check, are you looking for the method source code? – Mehdi Dehghani Jan 16 '20 at 05:29
  • I think it is simple, but not what you said. It must use the order of the items to know what to compare them with in the next renders. – Andres Zapata Jan 16 '20 at 05:30
  • [How does shallow compare work in react](https://stackoverflow.com/q/36084515/3367974), also [How to compare arrays in JavaScript?](https://stackoverflow.com/q/7837456/3367974) – Mehdi Dehghani Jan 16 '20 at 05:32

2 Answers2

1

There is function called areHookInputsEqual in ReactFiberHooks.js in react-reconciler here

This function is called from updateEffectImpl if prev dependencies and next dependencies are equal react won't push effect so it won't run.

Amit Chauhan
  • 6,151
  • 2
  • 24
  • 37
  • 1
    Amit, perfect. This is what i was looking for: for (let i = 0; i < prevDeps.length && i < nextDeps.length; i++) { if (is(nextDeps[i], prevDeps[i])) { continue; } return false; } return true; – Andres Zapata Jan 16 '20 at 05:38
0

How does useEffect decide how to compare items

in this case use effect will be called if value of name or count will change,that is name will not be compared to count but it will be compared to its previous value.

(note: you have used name that should be username)

Jatin Parmar
  • 2,759
  • 5
  • 20
  • 31