Created
August 4, 2020 09:58
-
-
Save f-ricci/9da9b61af2475f9cf8dbae7f2102d2e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// copy from response here https://stackoverflow.com/a/55189448. ALL CREDITS TO THE ORIGINAL AUTHOR https://stackoverflow.com/users/79247/retsam | |
// the only reason this gist exists is to not lose the content in case of question / answer deletion from stackoverflow | |
const useEffectDebugger = (func, inputs, prefix = "useEffect") => { | |
// Using a ref to hold the inputs from the previous run (or same run for initial run | |
const oldInputsRef = useRef(inputs); | |
useEffect(() => { | |
// Get the old inputs | |
const oldInputs = oldInputsRef.current; | |
// Compare the old inputs to the current inputs | |
compareInputs(oldInputs, inputs, prefix) | |
// Save the current inputs | |
oldInputsRef.current = inputs; | |
// Execute wrapped effect | |
func() | |
}, inputs); | |
}; | |
const compareInputs = (oldInputs, newInputs, prefix) => { | |
// Edge-case: different array lengths | |
if(oldInputs.length !== newInputs.length) { | |
// Not helpful to compare item by item, so just output the whole array | |
console.log(`${prefix} - Inputs have a different length`, oldInputs, newInputs) | |
console.log("Old inputs:", oldInputs) | |
console.log("New inputs:", newInputs) | |
return; | |
} | |
// Compare individual items | |
oldInputs.forEach((oldInput, index) => { | |
const newInput = newInputs[index]; | |
if(oldInput !== newInput) { | |
console.log(`${prefix} - The input changed in position ${index}`); | |
console.log("Old value:", oldInput) | |
console.log("New value:", newInput) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment