Skip to content
LATEST

🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.

Upgradix
Upgradix Code. Learn. Ship.
Updated Nov 25, 2026

Refs, DOM Access & Derived State with useRef and useMemo

Use useRef to access DOM elements (like focusing an input) or store mutable values without triggering a re-render. Compute derived state directly during render, and wrap heavy calculations in useMemo only when they actually slow down your UI.

Refs, DOM Access & Derived State with useRef and useMemo

Quick Answer: Use useRef to access DOM elements (like focusing an input) or store mutable values without triggering a re-render. Compute derived state directly during render, and wrap heavy calculations in useMemo only when they actually slow down your UI.

Imagine Meena manages the front desk at a busy Chennai hospital. Her React portal searches through 5,000 patient records in real time.

When a patient walks up, Meena clicks a Quick Search button to jump straight into the search box. She also toggles a Compact View switch to fit more rows on her screen.

If Meena's developer puts everything in useState, the app re-renders twice on every keystroke and freezes when she toggles Compact View. How do we fix this cleanly?

1. Why Do We Need useRef and Derived State?

The problem with putting everything in useState

Beginners often store filtered lists in useState and update them inside useEffect. They also store timer IDs in useState.

Example 1: Storing derived data and timer IDs in useState (Anti-pattern)

This works for 20 patients, but causes extra renders and lag with 5,000 records.

const [query, setQuery] = useState("");
const [filtered, setFiltered] = useState(patients); // Redundant state!
const [timerId, setTimerId] = useState(null);       // Triggers useless render!

useEffect(() => {
  setFiltered(patients.filter(p => p.name.includes(query)));
}, [query, patients]);

What happens when Meena types one letter

Render 1: query changes to "L" (shows old filtered list for a split second)
Effect runs: setFiltered() triggers another render
Render 2: filtered list finally updates (2 renders for 1 keystroke!)

This setup works on a small demo. However, it breaks down in a real hospital app.

  1. Every keystroke causes two renders instead of one.
  2. Saving a background timerId in state forces React to repaint the screen for no visual change.
  3. Toggling an unrelated switch like compactView re-filters all 5,000 patients again.

The solution: useRef, Derived State, and useMemo

useRef = a React hook that holds a mutable .current box whose changes never trigger a re-render.

Derived State = a value you calculate directly from existing props or state during render, instead of copying it into a new useState.

useMemo = a React hook that caches the result of an expensive calculation and only recomputes it when its dependencies change.

Live Cycle: How useRef Bypasses Renders & useMemo Caches Work

Watch Meena's PatientSearch.jsx handle 4 real actions without wasted work.

Action 1: Meena clicks Quick Search button Renders: 1

Bypass Track (0 Re-renders)

inputRef (DOM Access)
Calls inputRef.current.focus() Idle
timerRef (Mutable Value)
Stores timerRef.current = 42 Idle

Render Track (UI Updates)

useState (query / compact)
Triggers React re-render Waiting
useMemo (5,000 Patients)
Deps: [patients, query] Cached
useRef (No Render) useState (Triggers Render) useMemo Cache Active Operation

Notice that useRef never increments the Render counter, and toggling compactView gets an instant CACHE HIT from useMemo.

2. Using useRef for DOM Access and Mutable Values

useRef has two main jobs in React: touching a real browser DOM node, and remembering a mutable value across renders silently.

Example 2: Focusing the search box and storing a timer ID with useRef

Neither inputRef nor timerRef causes the component to re-render.

import { useRef, useState } from "react";

export function PatientHeader({ onLogSearch }) {
  const inputRef = useRef(null);   // 1. DOM element reference
  const timerRef = useRef(null);   // 2. Mutable timer ID

  function handleQuickFocus() {
    inputRef.current?.focus();     // Direct DOM access
  }

  function handleSearchChange(text) {
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => onLogSearch(text), 400);
  }

  return (
    <div>
      <input ref={inputRef} onChange={e => handleSearchChange(e.target.value)} />
      <button onClick={handleQuickFocus}>Quick Search</button>
    </div>
  );
}

When React mounts the <input>, it places the real DOM node inside inputRef.current. Clicking the button focuses the cursor immediately with zero re-renders.

Updating timerRef.current remembers the timeout ID across renders, so we can cancel old timers cleanly without touching useState.

3. Computing Derived State Cleanly with useMemo

If a value can be calculated from existing state or props, do not store it in useState. Just compute it as a normal variable during render.

For small lists (under a few hundred items), a plain variable is already fast enough. When filtering 5,000 hospital records on every render, wrap that calculation in useMemo.

Example 3: Memoizing a 5,000-patient filter with useMemo

Toggling compactView re-renders the UI, but skips the heavy filter loop.

import { useMemo, useState } from "react";

export function PatientList({ patients }) {
  const [query, setQuery] = useState("");
  const [compactView, setCompactView] = useState(false);

  // Simple derived value: no useMemo needed
  const cleanQuery = query.trim().toLowerCase();

  // Heavy derived value: cached until patients or cleanQuery changes
  const visiblePatients = useMemo(() => {
    return patients.filter(p => p.name.toLowerCase().includes(cleanQuery));
  }, [patients, cleanQuery]);

  return (
    <div>
      <button onClick={() => setCompactView(v => !v)}>Toggle Compact</button>
      <p>Matches: {visiblePatients.length}</p>
    </div>
  );
}

Expected console trace

Typing "Lakshmi" -> useMemo ran (filtered 5,000 rows in 4 ms)
Clicking Toggle Compact -> useMemo skipped (Cache Hit, 0 ms)

Notice how cleanQuery stays a plain variable, while visiblePatients uses useMemo. Both are derived state, and neither needs useEffect.

4. useState vs. useRef vs. useMemo

Choosing between useState, useRef, and useMemo
Hook Triggers Re-render? Best Used For
useState Yes Data shown on screen (search text, toggles, modals).
useRef No DOM focus/scroll, timer IDs, previous values.
useMemo No (runs during render) Caching expensive derived calculations or stable object references.

The important terms to remember

  • Mutable Ref = an object ({ current: value }) that keeps the same memory reference across every render.
  • Derived State = data computed from existing state/props rather than duplicated in useState.
  • Dependency Array = the [patients, cleanQuery] list that tells useMemo when to recompute.

Design tip: Always start with a plain derived variable first. Only add useMemo after you measure a real slowdown or need referential equality for a memoized child component.

5. Common Mistakes to Avoid

1. Copying derived state into useState + useEffect

Storing filteredPatients in useState and syncing it with useEffect causes an extra render and brief stale UI.

Better approach: Compute filteredPatients directly during render, or wrap it in useMemo.

2. Reading or writing ref.current during render

Changing countRef.current++ inside the component body makes your UI unpredictable in React Strict Mode.

Better approach: Only read or write ref.current inside event handlers or useEffect.

3. Wrapping every tiny operation in useMemo

Using useMemo for a + b or query.trim() adds memory overhead and makes code harder to read without saving time.

Better approach: Reserve useMemo for heavy loops, sorting large tables, or preventing child re-renders.

6. Interview Questions & Practice

Question 1: What is the difference between useRef and useState?

What the interviewer expects: Clear knowledge of re-render behavior and real use cases for each hook.

Strong answer: "Both useState and useRef keep values alive between renders. The key difference is that updating useState triggers a re-render so the UI updates, while mutating ref.current does not. In Meena's hospital portal, I use useState for the search text shown on screen, and useRef to focus the search input or store a debounce timer ID."

Question 2: When should you use useMemo instead of a regular variable?

What the interviewer expects: Practical judgment on derived state and avoiding premature optimization.

Strong answer: "First, I always avoid putting derived state in useState. For simple math or small arrays, a plain variable during render is fastest and cleanest. I only reach for useMemo when the calculation is genuinely expensive—like filtering 5,000 patient records while the user toggles an unrelated compact view—or when passing a stable object to a React.memo child."

What interviewers expect at different levels

  • Junior developer: Knows how to focus an input with useRef and avoids storing simple totals in useState.
  • Senior developer: Explains why useState + useEffect causes double renders and knows when useMemo actually helps.
  • Technical architect: Measures render bottlenecks with React Profiler before memoizing and understands referential stability across large component trees.

Beginner: Railway ticket OTP input

Build a 4-box OTP verification form where typing a digit automatically moves focus to the next input box using useRef.

Expected result: The cursor jumps from box 1 to box 4 smoothly without extra re-renders.

Intermediate: UPI transaction history filter

Create a UPI passbook component with 2,000 transactions, a search bar, and a "Hide Amounts" privacy toggle. Derive the filtered list with useMemo.

Hint: Keep hideAmounts out of the useMemo dependency array so toggling privacy never re-filters the 2,000 rows.

Advanced: Live cricket scoreboard stopwatch

Build a match timer that tracks elapsed seconds, stores the setInterval ID in a ref, and also displays the previous over's run rate using a second ref.

  • Clear the interval safely on unmount.
  • Keep render count strictly to once per second.

Challenge: Add a "Reset & Focus Note" button that stops the timer and immediately focuses a commentary input box.

7. Next Steps

  • Open an existing React component and replace any useState + useEffect derived list with a direct calculation or useMemo.
  • Practice using the React DevTools Profiler to verify that toggling unrelated UI state hits your useMemo cache.

Discussion & Comments

0
Guest mode · Login / Register
Post directly as a guest or log in first.

No comments yet

Start the discussion above — ask a question, share a tip, or reply to a comment.

This article is protected. Printing and saving as PDF are disabled.