Last active
March 30, 2020 18:06
-
-
Save reecelucas/e825e0b2d9e3ebaadeeb5068c46f0aca to your computer and use it in GitHub Desktop.
React hook to get a previous prop/state 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'; | |
/** | |
* 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