Created
February 24, 2022 16:55
-
-
Save bpander/b0524a5d4a33052f42e4ac6b2e78e584 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
import { useEffect, useRef } from 'react'; | |
export const usePreviousDifferent = <T>(value?: T): T | undefined => { | |
const shortTermRef = useRef<T | undefined>(value); | |
const longTermRef = useRef<T>(); | |
useEffect(() => { | |
shortTermRef.current = value; | |
return () => { longTermRef.current = value; }; | |
}, [value]); | |
return (shortTermRef.current === value) ? longTermRef.current : shortTermRef.current; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment