Created
November 4, 2020 13:50
-
-
Save takumifukasawa/995af0d11286b6e3eabd54b6a21b0aef to your computer and use it in GitHub Desktop.
React: custom hooks of caching previous value
This file contains hidden or 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"; | |
/** | |
* cache previous value | |
* | |
* ex) | |
* const [value, setValue] = useState<number>(0); | |
* const previewState = usePrevious(value); | |
* | |
* @export | |
* @template T | |
* @param {T} value | |
* @returns | |
*/ | |
export default function usePrevious<T>(value: T) { | |
const ref = useRef<T>(); | |
useEffect(() => { | |
ref.current = value; | |
}, [value]); | |
return ref.current; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment