Our hook to track the previous values looks pretty useful, so let's extract that into it's own custom React Hook called usePrevious
.
this took me a minute to understand.
function usePrevious(value) {
const ref = useRef()
useEffect(() => {
ref.current = value
})
return ref.current
}
until I remembered that useEffect()
will be only be called AFTER render. so the value
that you pass into usePrevious()
is setup to be used next time, and the ref.current which is returned is the one which was assigned last time.
function usePrevious(value) {
const ref = useRef()
useEffect(() => {
ref.current = value // this ref.current will be returned next time usePrevious is called.
})
return ref.current
// this ref.current was assigned last time usePrevious() was called. if this is the first time usePrevious() has been called, ref.current will be undefined (unless you assign it something in the useRef hook.)
}
... which is exactly the point of that function. it just took me a minute to figure out why it worked, what was going on. :)
Nice comment, @Brian... thanks for the tip!
@Brian thanks for that, I too had to stop and look at this, your comment helped!