Determine the source code for the second parameter
- You simply walk through the deps array, executing the object.is () method for each item
UseEffect Whether the second argument can be used with or
Copy useEffect according to useEffect source code
let memorizedState = [] / / check the hooks
let index = 0 // Hook array subscript
const useEffect = (fn, dependencies) = > {
if(memorizedState[index]){
// This is not the first execution
let lastDependencies = memorizedState[index] // Array of dependencies
// Loop to see if the dependencies are the same as last time
lethasChanged = ! areHookInputsEqual(dependencies, lastDependencies)if (hasChanged) {
// Execute the fn function if the dependency has a twist
index += 1
memorizedState[index] = dependencies
setTimeout(fn) // Set the macro to work after the component render
} else {
// Each hook occupies a subscript position to avoid program confusion
index += 1
memorizedState[index] = dependencies
}
}else{
// First execution
index += 1
memorizedState[index] = dependencies
setTimeout(fn)
}
}
const areHookInputsEqual = (nextDeps, prevDeps) = > {
if (prevDeps === null) {
return false
}
if(prevDeps.length === 0) {
return true
}
for (let i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
if (Object.is(nextDeps[i], prevDeps[i])) {
continue;
}
return false;
}
return true;
}
Copy the code
-
one =1 && two =1
- UseEffect receives the second actual parameter, two
- Change the value of one, and the parameter receives 1
- Modifying the value of two will pass in the actual value and trigger a callback
- The second argument in useEffect is equivalent to one? Two : false
-
one = 1 || two =1
- UseEffect receives the second argument with a value of 1
- The one modification passes in the value of one
- Modifying the value of two passes in the value of two
- The reason: In useEffect, hooks’ index will trigger an index change if it is changed to either one or two, so that the value is compared to the last one or two change, so that if one was changed to 3, This time the TOW value is 3 and the comparison does not trigger the callback.