Web Developer

|

Stockholm, Sweden

Delivering scalable solutions for
startups, enterprises, and agencies.

useRef

What is useRef?

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

jack black book meme

What is useRef?

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

How does it work?

You mark a DOM element with useRef like putting a bookmark on a page. Later, you can jump straight to that element and control it without React having to search for it again.

Example: Want to play/pause a video with a button? Use useRef to mark the video element, then tell React "go to the bookmark and play the video."

Creating a Ref

  • Import: import {useRef} from "react"
  • Create: const inputRef = useRef()
  • Attach: <input ref={inputRef} />

When to use refs?

  • Focusing elements
  • Controlling videos/audio (play, pause, etc.)
  • Selecting text
  • Integrating third-party DOM libraries

Storing Mutable Values

useRef can also store values that change without triggering re-renders. Think of it as a persistent pocket that survives component updates.

Why this matters: Re-renders are expensive. useRef lets you track things like timers or counters without forcing your component to re-render every time the value changes.

Key Points

  • No Re-renders: Changing a useRef value doesn't update your component
  • Persistent: Values survive through re-renders
  • Perfect for: Timers, counters, or controlling DOM elements directly
Web Developer
Harry Yates 2025®