Skip to content
ClapelloNotes by Barath
ReactCh 15 · 1/6
Core6 min readUpdated

React / 82

useRef: remember without re-rendering

TL;DR

A ref is a box with a .current property. It survives re-renders but never causes one. Use it for timer ids and to reach real DOM nodes.

The shape

import { useRef } from "react";
 
const countRef = useRef(0);   // { current: 0 }
 
countRef.current = countRef.current + 1; // change it whenever you like
  • useRef(initialValue) returns a plain object, { current: initialValue }.
  • React gives you the same object on every render.
  • You change it by assigning to .current. React isn't told, so nothing re-renders.

Ref vs state

useState

for what the screen shows

you call

setCount(count + 1)

React schedules a re-render

re-render

Component runs again

gets the new value as a fresh snapshot
commit

Screen shows the new count

useRef

for what the screen doesn't need

you write

countRef.current += 1

no re-render

the box

{ current: 4 }

same object on every render, now holding the new value
read it later

Used in a handler or effect

for example, to clear a timer or focus an input
Both survive re-renders. Only state tells React to draw the screen again. A ref is changed quietly and nobody is told.
useStateuseRef
Gives you[value, setValue]{ current: value }
Change it withthe setterref.current = …
Re-renders?YesNo
Inside one rendera fixed snapshotcan change at any time
Read it inrender, handlers, effectshandlers and effects

A ref vs state

Try it
renders: 1
clicksRef.current

on screen

0

console.log → 0

count (state)

on screen

0

each click re-renders the whole component

Click the ref button a few times: the console line changes, the screen and render count don't. Now click the state button once. The re-render picks up the ref's latest value.

Example: a timer you can stop

Timer.jsx
import { useRef, useState } from "react";
 
export default function Timer() {
  const [seconds, setSeconds] = useState(0);
  const intervalRef = useRef(null);
 
  function start() {
    if (intervalRef.current !== null) return; // already running
    intervalRef.current = setInterval(() => setSeconds((s) => s + 1), 1000);
  }
 
  function stop() {
    clearInterval(intervalRef.current);
    intervalRef.current = null;
  }
 
  return (
    <>
      <p>{seconds}s</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
    </>
  );
}

seconds is on screen, so it's state. The interval id is never shown, but stop needs it after many re-renders, so it lives in a ref. With let intervalId, every tick would re-render, the variable would start over as undefined, and Stop would clear nothing.

Refs to DOM nodes

The most common use: pass a ref object to an element's ref attribute, and React puts the real DOM node into .current.

SearchBar.jsx
import { useRef } from "react";
 
export default function SearchBar() {
  const inputRef = useRef(null);
 
  return (
    <>
      <input ref={inputRef} placeholder="Search dishes" />
      <button onClick={() => inputRef.current.focus()}>Search</button>
    </>
  );
}
  1. renderReact calls your component. On the first render inputRef.current is still null: the input doesn't exist yet.
  2. commitReact creates the <input> and sets inputRef.current to that DOM node.
  3. effectsEffects run. The node is ready: focus it, measure it, scroll to it.
  4. clicksEvent handlers can use it any time while the input is on the page.
  5. unmountThe input is removed and React sets inputRef.current back to null.
React fills ref.current during the commit and empties it when the element is removed. So read it in event handlers and effects, not while rendering.

React manages the DOM for you, but a few things can only be done by calling browser methods on a node:

JobCall
Focus an inputinputRef.current.focus()
Scroll to an elementitemRef.current.scrollIntoView({ behavior: "smooth", block: "nearest" })
Measure size or positionboxRef.current.getBoundingClientRect()
Play a videovideoRef.current.play()

Reach into the DOM

Try it
  • Masala dosa
  • Paneer wrap
  • Veg biryani
  • Chole bhature
  • Idli sambar
  • Pav bhaji
  • Mango lassi
  • Gulab jamun
  1. Click a button to see the call.
Each button reads a ref inside a click handler, after React has filled it in. Try resizing the window and measuring again.

Use refs for these "imperative" jobs only. Don't use them to change text, classes or children by hand: React owns that and will overwrite your changes on the next render.

Don't read or write refs during render

Don't

Touch the ref while rendering

function Counter() {
  const clicksRef = useRef(0);
  clicksRef.current++; // write during render
  return <p>Rendered {clicksRef.current} times</p>; // read during render
}

React may call your component more than once per update (StrictMode does it on purpose in development), so the write can run more often than you think. And React can't see ref changes, so the screen goes stale.

Do

Touch it in handlers and effects

function Counter() {
  const [clicks, setClicks] = useState(0);
  return (
    <button onClick={() => setClicks(clicks + 1)}>
      Clicked {clicks} times
    </button>
  );
}

If it's on screen, it's state. Refs are for handlers and effects.

Rendering should be pure: the same props and state give the same JSX, with no side effects. A ref breaks both halves. The react-hooks/refs rule in recent versions of the React Hooks ESLint plugin flags it for you.

One exception is allowed: creating something expensive once.

const playerRef = useRef(null);
if (playerRef.current === null) {
  playerRef.current = new VideoPlayer(); // runs on the first render only
}

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.