Created
June 19, 2020 17:38
-
-
Save danedavid/5fcfe154bb5c267e32bd2df84bc3e93f to your computer and use it in GitHub Desktop.
Optimized version of usePrevValues
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
usePrevValues( | |
useMemo(() => ({ | |
count, | |
upperCount | |
}), [count, upperCount]), | |
useCallback(prevValues => { | |
console.log("callback invoked"); | |
if (prevValues.count + 1 === count) { | |
console.log("inner done"); | |
} | |
if (prevValues.upperCount + 1 === upperCount) { | |
console.log("outer done"); | |
} | |
}, [count, upperCount]) | |
); |
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
const usePrevValues = (value, callback) => { | |
const prevValues = useRef(value); | |
useEffect(() => { | |
callback(prevValues.current); | |
return () => (prevValues.current = value); | |
}, [value, callback]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment