Skip to content

Instantly share code, notes, and snippets.

@reecelucas
Last active March 30, 2020 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reecelucas/e825e0b2d9e3ebaadeeb5068c46f0aca to your computer and use it in GitHub Desktop.
Save reecelucas/e825e0b2d9e3ebaadeeb5068c46f0aca to your computer and use it in GitHub Desktop.
React hook to get a previous prop/state value
import { useEffect, useRef } from 'react';
/**
* Usage:
* const [count, setCount] = useState(0);
* const prevCount = usePrevious(count);
*/
export default value => {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
// 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