Skip to content

Instantly share code, notes, and snippets.

@ronaldruzicka
Last active February 5, 2021 16:07
Show Gist options
  • Save ronaldruzicka/39730b60911e9e88db2742a4f87c836e to your computer and use it in GitHub Desktop.
Save ronaldruzicka/39730b60911e9e88db2742a4f87c836e to your computer and use it in GitHub Desktop.
React hook to use previous value in Typescript
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