Skip to content

Instantly share code, notes, and snippets.

@jeongtae
Last active September 16, 2023 17:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeongtae/896be1318c4b74b726262ba8d269aa9f to your computer and use it in GitHub Desktop.
Save jeongtae/896be1318c4b74b726262ba8d269aa9f to your computer and use it in GitHub Desktop.
usePrevious React hook in Typescript
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;
@jfitzsimmons
Copy link

I searched for "usePrevious react typescript" and this just saved me some headaches. Thanks!

@jeongtae
Copy link
Author

jeongtae commented Nov 5, 2021

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.

@riteshjagga
Copy link

Nice! Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment