Last active
December 13, 2024 23:12
-
-
Save jeongtae/896be1318c4b74b726262ba8d269aa9f to your computer and use it in GitHub Desktop.
usePrevious React hook 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 { useEffect, useRef } from 'react'; | |
function usePrevious<T>(value: T): T | undefined { | |
const ref = useRef<T>(); | |
useEffect(() => { | |
ref.current = value; | |
}, [value]); | |
return ref.current; | |
} | |
export default usePrevious; |
I searched for "usePrevious react typescript" and this just saved me some headaches. Thanks!
Thank you for using my code. However, I suggest you use the revised version just updated a moment ago. I replaced the return type T
with T | undefined
. Because usePrevious()
function will return undefined
when the first time to use it.
Nice! Thank you so much!
nice
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I searched for "usePrevious react typescript" and this just saved me some headaches. Thanks!