Created
February 12, 2023 06:58
-
-
Save Tim-W-James/6bbe6e1a258c3db1f4beefc05ad7547f to your computer and use it in GitHub Desktop.
React usePrevious Custom Hook #hooks
This file contains hidden or 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 usePrevious = <T>(value: T): T => { | |
// The ref object is a generic container whose current property is mutable ... | |
// ... and can hold any value, similar to an instance property on a class | |
const ref: any = useRef<T>(); | |
// Store current value in ref | |
useEffect(() => { | |
ref.current = value; | |
}, [value]); // Only re-run if value changes | |
// Return previous value (happens before update in useEffect above) | |
return ref.current; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment