Full Stack Development

useRef and DOM

by Tomas Trescak t.trescak@westernsydney.edu.au

useRef

When to use?

  • Accessing DOM elements (like input fields or divs).
  • Storing mutable values that do not trigger re-renders.

useRef

Key Points

  • useRef returns a mutable object with a current property:



  • The current property can hold:
    • A DOM element reference.
    • A mutable value that persists across renders.
    const myRef = useRef(initialValue);
const value = myRef.current;
  

useRef

/

Accessing DOM Elements

      import React, { render, useRef, useEffect } from "react";

const DomRefDemo = () => {
  const inputRef = useRef(null);

  useEffect(() => {
    // Focus the input field on component mount 
    inputRef.current.focus();
  }, []);

  return (
    <div>
      <h1>useRef Example: DOM Access</h1>
      <input 
        ref={inputRef} 
        type="text" 
        placeholder="I will be focused on load" />
    </div>
  );
};

render(<DomRefDemo />);
    

useRef

/

Storing Mutable Values without re-rendering

      import React, { useRef, useState, render } from "react";

const MutableRefDemo = () => {
  const renderCount = useRef(1);
  const [count, setCount] = useState(0);

  // Increment renderCount on each re-render
  renderCount.current += 1;

  return (
    <div>
      <h1>useRef Example: Mutable Values</h1>
      <p>
        Re-rendered: {renderCount.current} times
      </p>
      <p>State Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment Count
      </button>
    </div>
  );
};

render(<MutableRefDemo />);
    

useRef

/

Preserving Previous State or Value

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

const PreviousValueDemo = () => {
  const [count, setCount] = useState(0);
  const prevCount = useRef(count);

  useEffect(() => {
    prevCount.current = count; // Update the ref value after render
  }, [count]);

  return (
    <div>
      <h1>useRef Example: Preserve Previous State</h1>
      <p>Current Count: {count}</p>
      <p>Previous Count: {prevCount.current}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

render(<PreviousValueDemo />);
    

useRef

Conclusion

Feature useRef useState
Triggers Re-render ❌ No ✅ Yes
Mutable ✅ Yes (via current ) ✅ Yes (but causes re-render)
Usage DOM access, persisting values State management, triggering re-renders