Created
May 17, 2020 09:37
-
-
Save arekmaz/bf79645cc6c5883396c8fbca51712121 to your computer and use it in GitHub Desktop.
usePrevious vs usePreviousValue hooks
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
// This hook returns what the value was previously | |
// even across multiple renders | |
// (correct for the | |
// "<button>Value: {value}, previous: {previousValue}</button>" | |
// use case. | |
function usePreviousValue(value, defaultValue) { | |
const [prev, setPrev] = useState(defaultValue); | |
const next = useRef(); | |
useEffect(() => { | |
const old = next.current; | |
next.current = value; | |
setPrev(old); | |
}, [value]); | |
// Return previous value (happens before update in useEffect above) | |
return prev; | |
} | |
// This hook returns what the value was ON THE PREVIOUS RENDER | |
// (it will be equal to value if the component rerenders from | |
// other state change). | |
function usePrevious(value) { | |
const ref = useRef(); | |
useEffect(() => { | |
ref.current = value; | |
}); | |
return ref.current; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment