Track Values Over the Course of Renders with React useRef in a Custom usePrevious Hook

Share this video with your friends

Send Tweet

Our hook to track the previous values looks pretty useful, so let's extract that into it's own custom React Hook called usePrevious.

Brian Eichenberger
Brian Eichenberger
~ 6 years ago

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. :)

Halian Vilela
Halian Vilela
~ 5 years ago

Nice comment, @Brian... thanks for the tip!

Mickey
Mickey
~ 5 years ago

@Brian thanks for that, I too had to stop and look at this, your comment helped!