Skip to content

Instantly share code, notes, and snippets.

@wyeo
Last active January 17, 2020 12:41
Show Gist options
  • Save wyeo/2096c558d21556b38ba308919402ccf5 to your computer and use it in GitHub Desktop.
Save wyeo/2096c558d21556b38ba308919402ccf5 to your computer and use it in GitHub Desktop.
useTraceableState : get previous value of a state
import { useRef, useEffect, useState } from "react"
const usePreviousValue = (value: any) => {
const ref = useRef()
useEffect(() => {
ref.current = value
})
return ref.current
}
export const useTraceableState = (initialValue: any) => {
const [value, setValue] = useState(initialValue)
const prevValue = usePreviousValue(value)
return [prevValue, value, setValue]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment