React useRef Hook Deep Dive



At this point I think the useRef hook is one of the common pieces of React that I don’t have a great understanding of. I use it every now and again, usually following a code sample, and it works, so I move on. Sometimes however you get to a crossroads where a shallow understanding just doesn’t cut it anymore, and we need to really understand the rules and capabilities of this hook to move forward. I’m in such a place now. Let’s break down everything there is to know about this hook.

📘 React Docs: useRef

This video is also very good:

🎥 Youtube: Learn useRef in 11 minutes

Ref vs State

A ref is very similar to state in that it persists between renders. However the key difference is that a change in a ref will not cause your component to re-render.

Let’s look at a quick example. Say we want to track a basic count.

const theCount = useRef(0)

When we create this reference it creates an object that looks like this

{ current: 0 }

The reference object has only one property current which holds the value of the reference.

Then to reference that value you would call theCount.current.

In this way we can track a value in a component without ever causing it to re-render, but the value will persist across renders.