What comparison process does the useEffect React hook use?
After each keystroke, fruits goes from [] to []
It seems that you're under the impression that fruits
is re-assigning to a new array
after each key stroke which is not the case.
It is not comparing two new arrays, it is comparing the same label, which points to the same reference in the memory in this particular point of time.
Given:
var arr = [];
We can check if arr
reference has changed over time (if no mutations took place).
simple example:
var arr = [];
var arr2 = arr;
console.log('arr === arr ', arr === arr)
console.log('arr === arr2 ', arr === arr2)
arr = [];
console.log('---- After the change ----');
console.log('arr === arr ', arr === arr)
console.log('arr === arr2 ', arr === arr2)
A function which is being used to compare objects is practically a polyfill of Object.is
method. You can see it here in the source code:
https://github.com/facebook/react/blob/master/packages/shared/objectIs.js
And here's a function which compares prevDeps
with nextDeps
within useEffect
implementation:
https://github.com/facebook/react/blob/master/packages/react-reconciler/src/ReactFiberHooks.new.js#L1427
By the way, Object.is
is mentioned as a comparison algorhitm in the hooks API section of the docs, under useState
.