Last active
February 5, 2021 16:07
-
-
Save ronaldruzicka/39730b60911e9e88db2742a4f87c836e to your computer and use it in GitHub Desktop.
React hook to use previous value in Typescript
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 { useRef, useEffect } from 'react' | |
/** | |
* Saves previous value, if you need to compare it to a current value | |
* @param value - anything you need to store as a previous value | |
*/ | |
export const usePrevious = <T>(value: T) => { | |
const ref = useRef<T>() | |
// Store current value in ref | |
useEffect(() => { | |
ref.current = value | |
}, [value]) | |
// Return previous value (happens before update in useEffect above) | |
return ref.current as T | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment