Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 08 / Stage 2

useRef and the DOM

Goal: Use useRef for its two real jobs - a handle to a real DOM node (focus, scroll, measure) and a mutable instance variable that survives re-renders without causing one - tell both apart from useState, know the installed React version's idiom for forwarding a ref through a custom component, and know when reaching for a ref is the wrong move entirely. Time: ~3 hours · Level: comfortable with useState and useEffect (Parts 3 and 6)

What you will learn

  • What a ref actually is: useRef(initialValue) returns one plain object, { current: initialValue }, that React guarantees is the same object across every re-render of that component instance
  • Why changing ref.current never re-renders anything - React only re-renders in response to a state update, never because some object's field changed
  • Using a ref as a DOM handle: ref={someRef} on a JSX element hands that element's real DOM node to someRef.current once it exists, so an effect or a handler can call an imperative method React has no prop for (.focus(), .scrollIntoView())
  • Using a ref as a mutable instance variable that is never shown on screen: an interval id a different handler needs to clear later, or "the previous render's value" to compare against
  • The installed React version's idiom for forwarding a ref through a custom component - verified locally against [email protected] (Section 5)
  • When a ref is the wrong tool: anything the UI needs to react to as the user interacts belongs in useState, not a ref, because a ref's own change is invisible to React
  • This part's running examples: a ref-vs-state click counter, an auto-focusing restaurant search box, a scroll-to-section menu nav, a pausable price ticker, a pincode input forwarding its ref two ways, and a fare calculator that gets a ref-based shortcut wrong on purpose

A note on how this part is organised: same convention as Parts 1-7 - every examples/ and solutions/ file here is wired into this repo's own harness/ and actually executed before being shown below.

Topics in this part

Practice

Every exercise below is a React component (or a Broken/Fixed pair) in its own .jsx file, paired with a .test.jsx that actually renders and interacts with it using Testing Library/Vitest - the same verified-output rule as every example in this course. Exercises involving timers use vi.useFakeTimers(), the same way examples/04_interval_and_previous_value_refs.jsx does.


Exercise 1: Auto-focus the first OTP digit

Scenario: A Zomato-style login screen sends a 4-digit OTP and shows four single-digit boxes. The first box should already have focus the instant the screen appears, with no tap from the user. What to do: Write OtpFirstBox() with a ref on the first <input maxLength={1}> of four, and a useEffect that calls .focus() on it once, on mount.

Sample output (really run):

render OtpFirstBox -> the first digit box has focus, the other three do not

💡 Hint: this is examples/02_autofocus_search_box.jsx's RestaurantSearchBox shape exactly - one ref, one effect with an empty dependency array, one .focus() call.


Exercise 2: A page-view counter that silently never updates

Scenario: A product page wants to log how many times a "Notify me" button was clicked, but a teammate reached for a ref instead of state and the displayed count is stuck. What to do: Write NotifyMeCountWithRefBroken() (a clickCountRef, incremented on click, read directly into the JSX - the same shape as examples/01_ref_vs_state_no_rerender.jsx's ClickCounterWithRef) and NotifyMeCountWithStateFixed(), identical except for useState. Prove the broken version's displayed count never changes after three clicks, while the fixed version shows 3.

Sample output (really run, three clicks on each):

NotifyMeCountWithRefBroken:   "Notified: 0" the whole time (never re-renders)
NotifyMeCountWithStateFixed:  "Notified: 3" after the third click

💡 Hint: the ref's .current really is 3 internally by the end - the bug is entirely about React never being told to look at it again, not about the counting logic itself.


Exercise 3: A jump-to nav for IRCTC-style search results

Scenario: A train search results page groups results into three sections - "Available", "Waitlisted", "Cancelled" - and wants a sticky nav bar that jumps straight to any one of them. What to do: Write TrainResultsNav() with one ref per section (collected the same way examples/03_scroll_to_section_nav.jsx's sectionRefs is, keyed by section id) and three nav buttons, each calling .scrollIntoView({ behavior: "smooth" }) on its own section's node only.

Sample output (really run, click "Waitlisted"):

click "Waitlisted" -> scrollIntoView called on the Waitlisted section's own node
                       Available's and Cancelled's nodes: scrollIntoView NOT called

💡 Hint: give each section's DOM node its own vi.fn() in the test (an instance property shadows the shared prototype method) - that's what tells two different sections' scrollIntoView calls apart, the same fix this part's own examples/03_scroll_to_section_nav.test.jsx needed.


Exercise 4: A "price dropped by ₹X" banner using a previous-value ref

Scenario: A Flipkart-style product page re-fetches a price periodically (simulated here with a button, not a real timer) and wants to show "Price dropped by ₹X since you opened this page" - comparing the current price against whatever it was one update ago, without that comparison itself causing an extra render. What to do: Write PriceDropBanner({ initialPrice }) with a price state, a "Simulate price update" button that sets a new (lower) price, and a previousPriceRef updated inside a useEffect keyed on price - the same shape as examples/04_interval_and_previous_value_refs.jsx's previousPriceRef. Show "Price dropped by ₹X" only when the new price is lower than the ref's value.

Sample output (really run, starting at ₹2000, each click drops the price by ₹300):

initial render        -> no banner (nothing to compare against yet)
click "Simulate..." once -> "Price dropped by ₹300"
click "Simulate..." again -> "Price dropped by ₹300" (comparing 1400 against 1700, not against 2000)

💡 Hint: the ref update has to happen in its own effect, after the render that changed price - updating it directly in the render body would make "previous" and "current" the same value by the time the comparison runs.


Exercise 5: A reusable SearchInput that forwards its ref the React 19 way

Scenario: A filters panel has a "Clear filters" button that, besides clearing the filter state, should also put focus back on the search box - but the search box is its own reusable component, not a bare <input>, so the parent's ref needs to reach through it. What to do: Write SearchInput({ ref, ...rest }), a component wrapping a single <input>, accepting ref as a plain destructured prop (examples/05_ref_as_prop_react19.jsx's idiom - no forwardRef). Write FiltersPanel() holding a searchInputRef via useRef(null), rendering <SearchInput ref={searchInputRef} /> and a "Clear filters" button whose onClick calls searchInputRef.current.focus().

Sample output (really run, click "Clear filters"):

click "Clear filters" -> SearchInput's underlying <input> has focus

💡 Hint: this is exactly examples/05_ref_as_prop_react19.jsx's PincodeInputModernRef, renamed and actually used by a parent instead of just tested in isolation - the whole point of forwarding a ref is a parent reaching through a custom component down to the real DOM node.


Exercise 6: Find and fix a stale-live-counter bug

Scenario: A review form shows "X / 200 characters" below a <textarea>, meant to update as the shopper types. A teammate wrote:

export function CharacterCounterBroken() {
  const textRef = useRef(null);
  const charCount = textRef.current?.value.length || 0;
  return (
    <div>
      <textarea ref={textRef} maxLength={200} />
      <p>{charCount} / 200 characters</p>
    </div>
  );
}

QA reports the counter is always stuck at 0 / 200, no matter how much is typed. What to do: Write both CharacterCounterBroken (the code above, unchanged) and CharacterCounterFixed, which uses a controlled <textarea> (useState + onChange, Part 5's pattern, the same move examples/06_when_not_to_use_ref.jsx's FareCalculatorWithStateFixed makes) so the count is read from state instead of a ref.

Sample output (really run, type "great product" - 13 characters):

CharacterCounterBroken: "0 / 200 characters" (ref read once, at mount, never updates)
CharacterCounterFixed:  "13 / 200 characters" (recalculated on every keystroke)

💡 Hint: this part's Section 6 names the rule directly - anything the UI needs to show live as the user types belongs in useState, never read from a ref's current DOM value.

Show the solutions for Part 8 (12 files)

solutions/ex01_otp_first_box.jsx

// Exercise 1 solution: same shape as examples/02_autofocus_search_box.jsx -
// a ref on the DOM node, filled in by React after the first commit, focused
// inside a mount-only effect.
import { useEffect, useRef } from "react";

export function OtpFirstBox() {
  const firstBoxRef = useRef(null);

  useEffect(() => {
    firstBoxRef.current.focus();
  }, []);

  return (
    <div>
      <input ref={firstBoxRef} maxLength={1} aria-label="OTP digit 1" />
      <input maxLength={1} aria-label="OTP digit 2" />
      <input maxLength={1} aria-label="OTP digit 3" />
      <input maxLength={1} aria-label="OTP digit 4" />
    </div>
  );
}

solutions/ex01_otp_first_box.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { OtpFirstBox } from "./ex01_otp_first_box.jsx";

describe("OtpFirstBox", () => {
  it("really focuses only the first digit box on mount, with no tap from the user", () => {
    render(<OtpFirstBox />);

    expect(screen.getByLabelText("OTP digit 1")).toHaveFocus();
    expect(screen.getByLabelText("OTP digit 2")).not.toHaveFocus();
    expect(screen.getByLabelText("OTP digit 3")).not.toHaveFocus();
    expect(screen.getByLabelText("OTP digit 4")).not.toHaveFocus();
  });
});

solutions/ex02_notify_me_count.jsx

// Exercise 2 solution: same shape as examples/01_ref_vs_state_no_rerender.jsx -
// mutating a ref never re-renders, so a count read straight from .current
// into JSX goes stale on screen; useState fixes it with the identical logic.
import { useRef, useState } from "react";

export function NotifyMeCountWithRefBroken() {
  const clickCountRef = useRef(0);

  function handleClick() {
    clickCountRef.current += 1;
  }

  return (
    <div>
      <p>Notified: {clickCountRef.current}</p>
      <button onClick={handleClick}>Notify me</button>
    </div>
  );
}

export function NotifyMeCountWithStateFixed() {
  const [notifyCount, setNotifyCount] = useState(0);

  function handleClick() {
    setNotifyCount((current) => current + 1);
  }

  return (
    <div>
      <p>Notified: {notifyCount}</p>
      <button onClick={handleClick}>Notify me</button>
    </div>
  );
}

solutions/ex02_notify_me_count.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { NotifyMeCountWithRefBroken, NotifyMeCountWithStateFixed } from "./ex02_notify_me_count.jsx";

describe("NotifyMeCountWithRefBroken", () => {
  it("really stays at 'Notified: 0' no matter how many times the button is clicked", async () => {
    const user = userEvent.setup();
    render(<NotifyMeCountWithRefBroken />);
    const button = screen.getByRole("button", { name: "Notify me" });

    await user.click(button);
    await user.click(button);
    await user.click(button);

    expect(screen.getByText("Notified: 0")).toBeInTheDocument();
  });
});

describe("NotifyMeCountWithStateFixed", () => {
  it("really shows 3 after three clicks", async () => {
    const user = userEvent.setup();
    render(<NotifyMeCountWithStateFixed />);
    const button = screen.getByRole("button", { name: "Notify me" });

    await user.click(button);
    await user.click(button);
    await user.click(button);

    expect(screen.getByText("Notified: 3")).toBeInTheDocument();
  });
});

solutions/ex03_train_results_nav.jsx

// Exercise 3 solution: same shape as examples/03_scroll_to_section_nav.jsx -
// one ref per section, collected by section id inside a single useRef.
import { useRef } from "react";

const SECTIONS = ["available", "waitlisted", "cancelled"];
const SECTION_LABELS = {
  available: "Available",
  waitlisted: "Waitlisted",
  cancelled: "Cancelled",
};

export function TrainResultsNav() {
  const sectionRefs = useRef({});

  function scrollToSection(sectionId) {
    sectionRefs.current[sectionId]?.scrollIntoView({ behavior: "smooth" });
  }

  return (
    <div>
      <nav>
        {SECTIONS.map((sectionId) => (
          <button key={sectionId} onClick={() => scrollToSection(sectionId)}>
            {SECTION_LABELS[sectionId]}
          </button>
        ))}
      </nav>
      {SECTIONS.map((sectionId) => (
        <section
          key={sectionId}
          data-testid={`section-${sectionId}`}
          ref={(node) => {
            sectionRefs.current[sectionId] = node;
          }}
        >
          <h2>{SECTION_LABELS[sectionId]}</h2>
        </section>
      ))}
    </div>
  );
}

solutions/ex03_train_results_nav.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { TrainResultsNav } from "./ex03_train_results_nav.jsx";

describe("TrainResultsNav", () => {
  it("really scrolls only the clicked section's own node", async () => {
    const user = userEvent.setup();
    render(<TrainResultsNav />);

    const available = screen.getByTestId("section-available");
    const waitlisted = screen.getByTestId("section-waitlisted");
    const cancelled = screen.getByTestId("section-cancelled");
    available.scrollIntoView = vi.fn();
    waitlisted.scrollIntoView = vi.fn();
    cancelled.scrollIntoView = vi.fn();

    await user.click(screen.getByRole("button", { name: "Waitlisted" }));

    expect(waitlisted.scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth" });
    expect(available.scrollIntoView).not.toHaveBeenCalled();
    expect(cancelled.scrollIntoView).not.toHaveBeenCalled();
  });
});

solutions/ex04_price_drop_banner.jsx

// Exercise 4 solution: same shape as
// examples/04_interval_and_previous_value_refs.jsx's previousPriceRef - a
// ref updated AFTER the render that changed the value it tracks, so this
// render can diff against "before" without that diff causing a render.
import { useEffect, useRef, useState } from "react";

export function PriceDropBanner({ initialPrice }) {
  const [price, setPrice] = useState(initialPrice);
  const previousPriceRef = useRef(initialPrice);
  const hasComparedOnceRef = useRef(false);

  const previousPrice = previousPriceRef.current;
  const droppedBy = hasComparedOnceRef.current && price < previousPrice ? previousPrice - price : null;

  useEffect(() => {
    previousPriceRef.current = price;
    hasComparedOnceRef.current = true;
  }, [price]);

  function handleSimulateUpdate() {
    setPrice((current) => current - 300);
  }

  return (
    <div>
      <p>Price: ₹{price}</p>
      {droppedBy !== null && <p>Price dropped by ₹{droppedBy}</p>}
      <button onClick={handleSimulateUpdate}>Simulate price update</button>
    </div>
  );
}

solutions/ex04_price_drop_banner.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { PriceDropBanner } from "./ex04_price_drop_banner.jsx";

describe("PriceDropBanner", () => {
  it("really shows no banner on first render, then ₹300 drops compared against the last price only", async () => {
    const user = userEvent.setup();
    render(<PriceDropBanner initialPrice={2000} />);

    expect(screen.getByText("Price: ₹2000")).toBeInTheDocument();
    expect(screen.queryByText(/Price dropped by/)).not.toBeInTheDocument();

    const button = screen.getByRole("button", { name: "Simulate price update" });
    await user.click(button);
    expect(screen.getByText("Price: ₹1700")).toBeInTheDocument();
    expect(screen.getByText("Price dropped by ₹300")).toBeInTheDocument();

    await user.click(button);
    expect(screen.getByText("Price: ₹1400")).toBeInTheDocument();
    // Compared against 1700 (the previous render's price), not 2000 - still
    // exactly ₹300, proving the ref really tracks "last render", not "first".
    expect(screen.getByText("Price dropped by ₹300")).toBeInTheDocument();
  });
});

solutions/ex05_search_input_forward_ref.jsx

// Exercise 5 solution: same shape as examples/05_ref_as_prop_react19.jsx's
// PincodeInputModernRef - ref declared as a plain destructured prop, React
// 19 idiom, actually used here by a parent reaching through to the DOM node.
import { useRef, useState } from "react";

export function SearchInput({ ref, ...rest }) {
  return <input placeholder="Search filters" {...rest} ref={ref} />;
}

export function FiltersPanel() {
  const searchInputRef = useRef(null);
  const [query, setQuery] = useState("");

  function handleClearFilters() {
    setQuery("");
    searchInputRef.current.focus();
  }

  return (
    <div>
      <SearchInput ref={searchInputRef} value={query} onChange={(event) => setQuery(event.target.value)} />
      <button onClick={handleClearFilters}>Clear filters</button>
    </div>
  );
}

solutions/ex05_search_input_forward_ref.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { FiltersPanel } from "./ex05_search_input_forward_ref.jsx";

describe("FiltersPanel", () => {
  it("really focuses SearchInput's underlying <input> through the forwarded ref when Clear filters is clicked", async () => {
    const user = userEvent.setup();
    render(<FiltersPanel />);

    const input = screen.getByPlaceholderText("Search filters");
    await user.type(input, "pizza");
    expect(input).toHaveValue("pizza");

    await user.click(screen.getByRole("button", { name: "Clear filters" }));

    expect(input).toHaveValue("");
    expect(input).toHaveFocus();
  });
});

solutions/ex06_character_counter.jsx

// Exercise 6 solution: same shape as examples/06_when_not_to_use_ref.jsx -
// a value the UI must show live as the user types belongs in useState, not
// read from a ref's DOM value.
import { useRef, useState } from "react";

export function CharacterCounterBroken() {
  const textRef = useRef(null);
  const charCount = textRef.current?.value.length || 0;

  return (
    <div>
      <textarea ref={textRef} maxLength={200} />
      <p>{charCount} / 200 characters</p>
    </div>
  );
}

export function CharacterCounterFixed() {
  const [text, setText] = useState("");

  return (
    <div>
      <textarea maxLength={200} value={text} onChange={(event) => setText(event.target.value)} />
      <p>{text.length} / 200 characters</p>
    </div>
  );
}

solutions/ex06_character_counter.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { CharacterCounterBroken, CharacterCounterFixed } from "./ex06_character_counter.jsx";

describe("CharacterCounterBroken", () => {
  it("really stays stuck at '0 / 200 characters' while typing", async () => {
    const user = userEvent.setup();
    render(<CharacterCounterBroken />);

    await user.type(screen.getByRole("textbox"), "great product");
    expect(screen.getByText("0 / 200 characters")).toBeInTheDocument();
  });
});

describe("CharacterCounterFixed", () => {
  it("really updates the count on every keystroke", async () => {
    const user = userEvent.setup();
    render(<CharacterCounterFixed />);

    await user.type(screen.getByRole("textbox"), "great product");
    expect(screen.getByText("13 / 200 characters")).toBeInTheDocument();
  });
});

Common mistakes

Mistake Why it is wrong Fix
Expecting the screen to update after mutating someRef.current Changing a ref's .current never tells React to re-render - only a state update does If the UI needs to show it, use useState instead (Section 1)
Reading someRef.current inside the render body on the very first render, before anything is mounted The DOM node a ref points at does not exist until after React commits the render to the screen - it is null until then Read/call methods on a DOM ref inside useEffect (runs after commit) or an event handler, never directly in the render body (Section 2)
Using a ref to read an input's value so it can drive what's shown on screen as the user types A ref's change is invisible to React - the displayed value only reflects what the ref held at whatever render last ran, not the live DOM value Use a controlled input (useState + onChange, Part 5) for anything the UI must reflect live; a ref-read value is only safe to read once, at a moment something else already re-renders for, e.g. a submit (Section 6)
Writing a custom component that accepts ref the old way (a second forwardRef function argument) when a plain destructured ref prop already works on the installed version Not wrong, exactly, but unnecessary ceremony - forwardRef is still supported but no longer required on [email protected] Declare ref as a normal destructured prop on a plain function component (Section 5) - reach for forwardRef only when reading older code
Reaching for useRef to "skip a re-render" on a value the UI does need to show eventually Trades a correctness bug (stale UI) for a render you didn't want to pay for - the render was correct, it just wasn't profiled as a problem yet Only optimize renders after measuring a real one is slow (Part 12) - useRef is not a performance tool, it is for values the UI was never meant to show live

Quick recap

  • useRef(initialValue) returns the same { current: initialValue } object on every re-render; mutating .current is instant but invisible to React - it never causes a re-render by itself.
  • A ref's most common job is a DOM handle: ref={someRef} on a JSX element fills in someRef.current with the real DOM node once it exists, letting an effect or handler call an imperative method (.focus(), .scrollIntoView()) React has no prop for.
  • A ref's other job is a mutable instance variable - an interval id a different handler needs later, or a "previous value" to diff against - never shown on screen, never meant to drive a render.
  • On [email protected] (verified locally), a custom component accepts a forwarded ref by simply declaring ref as a normal prop; forwardRef still works but is legacy, needed only on older React versions or in older code you're reading.
  • If a value needs to be shown, recalculated, or reacted to live as the user interacts, it belongs in useState, never a ref - a ref's own change is invisible to React, full stop.

Checklist

  • I can say, in one sentence, why mutating .current never re-renders anything.
  • I wrote (or found) a component that focuses or scrolls a real DOM node via a ref, inside an effect, not directly in the render body.
  • I wrote a component with two refs doing two different non-DOM jobs (an interval id and a previous value), and proved both with a real test the way examples/04_interval_and_previous_value_refs.test.jsx does.
  • I checked this course's installed React version's ref-forwarding idiom myself (or read Section 5's verified result) instead of assuming forwardRef is still required.
  • I reproduced the Section 6 mistake myself - read a ref's value to compute something the UI should show live, watched it go stale while typing - then fixed it with useState.
  • I can name, without looking it up, the two legitimate jobs of useRef and at least one case where reaching for it instead of useState would be wrong.

Search the guide