Skip to content

Instantly share code, notes, and snippets.

@Tim-W-James
Created February 12, 2023 06:58
Show Gist options
  • Save Tim-W-James/6bbe6e1a258c3db1f4beefc05ad7547f to your computer and use it in GitHub Desktop.
Save Tim-W-James/6bbe6e1a258c3db1f4beefc05ad7547f to your computer and use it in GitHub Desktop.
React usePrevious Custom Hook #hooks
const usePrevious = <T>(value: T): T => {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance property on a class
const ref: any = useRef<T>();
// Store current value in ref
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
// Return previous value (happens before update in useEffect above)
return ref.current;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment