useRef Example: Capturing Previous State

Sam Dent
3 min readNov 30, 2020

This is an article to demonstrate one use of the useRef hook for those newer to react and hooks.

I’ll be looking at the example from the React docs on how to access a components previous state 👇

I think it’s a good example of what the useRef hook can do and why it’s a great tool to have in the developer tool kit. Plus if React are demoing it, you know it’s legit 😇.

useRef is really powerful because of the fact it creates a good ol’ fashioned javascript object. No fancy shmancy React elements here, just that vanillaJS that we know and love.

This object extists throughout a components lifecycle and … wait for it, persists through re-renders! Woah

Existing and persisting is what we’re ALL about.

Let’s get into it.

capturing the previous state with useRef

To break it down we have a Counter component with some state, count.

Next is a variable prevCountRef, you’ll often see variables named with the -Ref suffix when useRef is involved. Without conventions we’re just animals.

prevCountRef takes the result of the useRef() call as it’s value, now you might be wondering what that value is. As we know now, useRef is going to return us an object and that object has a single current property with a value of whatever pass to the hook.

const prevCountRef = useRef();

Wait!! We didn’t pass anything to the useRef() hook!!

Well observed clever clogs. When this happens the current value is initialised as undefined so we get an object that looks like this:

{current: undefined}

Now(ish) we have a useEffect() call which updates prevCountRef.current to the value of count.

useEffect(() => {
prevCountRef.current = count;
});

BUT remember this is a callback which will only happen once the Counter function has returned it’s sweet sweet JSX and mounted to the DOM.

So actually the next thing to happen chronologically is the initialisation of our next variable prevCount with the value of prevCountRef.current.

Then we return an h1, displaying the count state and prevCount variable, which gets rendered in the browser. Once this happens the useEffect call is triggered for realz.

If we imagine the very first rendering of this component the JSX returned would hold these values.

<h1>Now: 0, before: undefined<h1>

Only when this is returned and the component successfully mounted to the DOM will the prevCountRef.current take the value of count. This magic of asynchronicity from useEffect combined with useRef’s hardy, never-say-die, unyielding persistence mean we can keep this components previous state value handy everytime it re-renders!

Pretty great stuff, useRef is really handy for exactly this reason.

And if you’re not totally satisfied with all you’ve seen so far why not have a lovely custom usePrevious hook from those lovely folk at React free of charge!

Now you can reuse this hook goodness all over your code.

--

--

Sam Dent

Adventuring in the world of software development.