Skip to content

Instantly share code, notes, and snippets.

@arekmaz
Created May 17, 2020 09:37
Show Gist options
  • Save arekmaz/bf79645cc6c5883396c8fbca51712121 to your computer and use it in GitHub Desktop.
Save arekmaz/bf79645cc6c5883396c8fbca51712121 to your computer and use it in GitHub Desktop.
usePrevious vs usePreviousValue hooks
// 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