Harry Yates

I'm a web developer focused on TypeScript, React, and Three.js.

useRef

Mon, 26th Feb 2024
What is useRef?

It's like creating a bookmark so you can quickly find and interact with a specific part of your webpage (such as a video player or an input field) without having to search the entire page every time.

Post

How does it work?

Imagine you have a book (your component) and want to quickly mark a page (a DOM element) to open it later. You insert a bookmark (useRef) on that page. Now, you can open the book directly to that page without flipping through it whenever you want.

Example: If you have a video on your website and you want to play or pause it with a button, you can use useRef to mark the video. Later, you just tell React, "Hey, go to the bookmark and play the video," without React needing to search for the video again.

create a ref
  1. Import the useRef hook (named export) from the react package. import {useRef} from "react";.
  2. Create a new ref at the top of the component (rules of hooks). For example, const inputRef = useRef();.
  3. Assign the created ref to the JSX element that you're rendering, using the ref attribute. For example, <input ref={inputRef} />.
When to use refs?

You might be tempted to use refs in every component, but refs are not commonly used. There are specific use cases for when refs should be used, such as:

  • Focusing an element.
  • Playing a video (videoElement.play()), pausing a video, etc.
  • Selecting text from the DOM.
  • Initialising DOM libraries.

Storing Mutable Values

Beyond DOM Elements

useRef isn't just for bookmarks in a book. It can also be like a pocket in your notebook where you can keep notes or reminders.

These notes are special because changing them doesn’t require rewriting the whole page (or re-rendering your component).

Mutable Values

These are things that can change, like scores in a game or a stopwatch timer.

With useRef, you can change these values all you want; the rest of the page doesn't need to be updated (or re-render) every time a change happens.

useRef helps maintain smooth and responsive user interfaces. Re-renders can be costly, especially for complex components or applications, requiring recalculating the component's state and potentially re-executing side effects.

Persistence

The pocket in your notebook (or useRef) keeps your notes safe even if you turn the page. Similarly, useRef keeps the values safe and unchanged through re-renders of your component.

Usage Notes

No Re-renders

Updating a useRef value is like changing the note in your pocket; the notebook’s page stays the same.

This means your component doesn't update its appearance because something useRef changed.

Why use it?

It's perfect when you need to keep track of something continuously (like a timer) or control parts of your webpage (like a video or animation) without updating the whole page every time something small changes.