⚛️ React useRef Hook

Chapter 14 of 15

What is useRef?

The useRef Hook allows you to persist values between renders without causing a re-render. It can also be used to access DOM elements directly.

💡 Two Main Uses:
  1. Accessing DOM elements
  2. Storing mutable values that persist across renders

Does Not Cause Re-renders

If we tried to count renders using useState, we'd create an infinite loop:

// ❌ This creates an infinite loop!
import { useState, useEffect } from "react";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(count + 1); // ❌ Causes re-render, triggers useEffect again!
  });

  return <div>Render Count: {count}</div>;
}

useRef solves this problem:

// ✅ This works!
import { useState, useEffect, useRef } from "react";

function App() {
  const [inputValue, setInputValue] = useState("");
  const count = useRef(0);

  useEffect(() => {
    count.current = count.current + 1;
  });

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h1>Render Count: {count.current}</h1>
    </>
  );
}
✨ Key Point: Updating count.current doesn't trigger a re-render!

Accessing DOM Elements

useRef is commonly used to access DOM elements directly:

import { useRef } from "react";

function App() {
  const inputElement = useRef();

  const focusInput = () => {
    inputElement.current.focus();
  };

  return (
    <>
      <input type="text" ref={inputElement} />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

Tracking State Changes

useRef can track previous state values:

import { useState, useEffect, useRef } from "react";

function App() {
  const [inputValue, setInputValue] = useState("");
  const previousInputValue = useRef("");

  useEffect(() => {
    previousInputValue.current = inputValue;
  }, [inputValue]);

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h2>Current Value: {inputValue}</h2>
      <h2>Previous Value: {previousInputValue.current}</h2>
    </>
  );
}

Common Use Cases

1. Focus Management

function LoginForm() {
  const usernameRef = useRef();

  useEffect(() => {
    // Focus username on mount
    usernameRef.current.focus();
  }, []);

  return <input ref={usernameRef} placeholder="Username" />;
}

2. Storing Timer IDs

function Timer() {
  const [count, setCount] = useState(0);
  const timerRef = useRef();

  const start = () => {
    timerRef.current = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
  };

  const stop = () => {
    clearInterval(timerRef.current);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
    </div>
  );
}

3. Measuring Element Size

function MeasureDiv() {
  const divRef = useRef();

  const logSize = () => {
    console.log(divRef.current.offsetWidth);
    console.log(divRef.current.offsetHeight);
  };

  return (
    <>
      <div ref={divRef} style={{ width: "200px", height: "100px" }}>
        Measure me!
      </div>
      <button onClick={logSize}>Log Size</button>
    </>
  );
}

4. Scroll to Element

function ScrollExample() {
  const bottomRef = useRef();

  const scrollToBottom = () => {
    bottomRef.current.scrollIntoView({ behavior: "smooth" });
  };

  return (
    <div>
      <button onClick={scrollToBottom}>Scroll to Bottom</button>
      {/* Long content */}
      <div ref={bottomRef}>Bottom of page</div>
    </div>
  );
}

useRef vs useState

Feature useRef useState
Triggers Re-render ❌ No ✅ Yes
Mutable ✅ Yes (current) ❌ No (immutable)
Updates Synchronous Asynchronous
Use For DOM access, timers UI state

Multiple Refs

You can use multiple refs in a single component:

function MultipleRefs() {
  const inputRef1 = useRef();
  const inputRef2 = useRef();
  const inputRef3 = useRef();

  const focusFirst = () => inputRef1.current.focus();
  const focusSecond = () => inputRef2.current.focus();
  const focusThird = () => inputRef3.current.focus();

  return (
    <div>
      <input ref={inputRef1} placeholder="First" />
      <input ref={inputRef2} placeholder="Second" />
      <input ref={inputRef3} placeholder="Third" />
      <button onClick={focusFirst}>Focus First</button>
      <button onClick={focusSecond}>Focus Second</button>
      <button onClick={focusThird}>Focus Third</button>
    </div>
  );
}

Best Practices

⚠️ Important: In React, you should generally let React handle DOM updates. Use refs only when you need to do something that React can't handle declaratively.

When to Use useRef

✅ Good Use Cases:
  • Managing focus, text selection, or media playback
  • Triggering imperative animations
  • Integrating with third-party DOM libraries
  • Storing mutable values without causing re-renders
  • Keeping reference to timer/interval IDs

What's Next?

Now that you understand useRef, you're ready to learn about Custom Hooks - how to create your own reusable hooks!