useRef: remember without re-rendering

React chapter 142 · useRef · timers · DOM nodes · instance values · source: react.dev/learn/referencing-values-with-refs

The problem

A stopwatch keeps its interval id in a plain let. Every tick re-renders, which re-runs the function and resets the variable, so Stop cannot find the timer. Pressing Start again stacks a second interval and the clock runs at double speed.

The pattern that fixes it

useRef gives the component one box that survives every render: timer.current = setInterval(…). Stop reads the same box and clears the right interval. Writing to a ref does not re-render, which is exactly right for values the screen never shows.

In plain words

Each render is a fresh run of your function, so normal variables are forgotten. State is remembered and redraws the screen. A ref is remembered and does not redraw anything.

A sticky note on the fridge. Whoever walks into the kitchen (each render) finds the same note; changing it does not make anyone repaint the kitchen.

Terms

ref
An object { current } that React keeps for the life of the component. The same object every render.
instance value
Data the component needs to remember but not display: timer ids, the previous value, a DOM node.
ref to a DOM node
<input ref={inputRef} /> — React puts the element in inputRef.current after commit.

Going deeper

State vs ref vs variable

Ask two questions. Must it survive a re-render? If not, a variable is fine. Does the screen depend on it? If yes, state; if no, ref. Storing a timer id in state works but costs an extra render for nothing; storing a counter you display in a ref leaves the screen stale.

Do not read or write refs during render

Render must be pure and may run more than once (StrictMode, concurrent rendering). Read and write ref.current in event handlers and effects. The one exception is lazy initialization: if (ref.current === null) ref.current = createExpensiveThing().

Where refs show up in this course

Fork refs (3), imperative handles (95), debounce with refs (96), the latest-value pattern behind useEffectEvent (15), and render counters in these labs, which write a ref in an effect so StrictMode cannot double-count.

Keep learning

Overview

Real life: a stopwatch, a polling timer, a debounce, an animation frame id.

Stop does nothing; Start twice runs two clocks.

The id was saved in a variable that belonged to one render. The next tick rendered again and made a new, empty variable. Press Start, then Stop. It keeps running. Press Start again: “intervals running” becomes 2 and the clock speeds up. tick → mono tb stop(): clearInterval(null) interval #7 orphaned, still ticking useRef box · kept by React writing it: Same stopwatch. Put the timer id in the one place that outlives renders. Why the variable forgets and the ref remembers Stop runs with render 3’s variable: null. Interval 7 can never be cleared. Where the timer id is stored store it in… survives a re-render? changing it re-renders? use for values computed and used within one render anything the screen shows timer ids, DOM nodes, previous values, flags

Stop finds the timer, every time.

useState also works, but spends a render to store an id nobody sees. useRef remembers it for free. Try all three.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.