Last active
January 17, 2020 12:41
-
-
Save wyeo/2096c558d21556b38ba308919402ccf5 to your computer and use it in GitHub Desktop.
useTraceableState : get previous value of a state
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, 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