Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created November 4, 2020 13:50
Show Gist options
  • Save takumifukasawa/995af0d11286b6e3eabd54b6a21b0aef to your computer and use it in GitHub Desktop.
Save takumifukasawa/995af0d11286b6e3eabd54b6a21b0aef to your computer and use it in GitHub Desktop.
React: custom hooks of caching previous value
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