JAVASCRIPT

Accessing DOM Elements with `useRef`

Learn how to directly interact with DOM elements or store mutable values without triggering re-renders using React's `useRef` hook.

import React, { useRef } from 'react';

function DOMInteractionComponent() {
  const inputRef = useRef(null);
  const mutableValueRef = useRef(0); // For storing mutable values

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

  const incrementMutableValue = () => {
    mutableValueRef.current += 1;
    console.log('Mutable value (does not trigger re-render):', mutableValueRef.current);
    // Note: Changing useRef.current does not trigger a re-render.
    // To show its current value in UI, you'd need useState or another trigger.
  };

  return (
    <div>
      <h1>useRef Example</h1>
      <input type="text" ref={inputRef} placeholder="Focus me" />
      <button onClick={focusInput}>Focus Input</button>
      <p>Check console for mutable value updates.</p>
      <button onClick={incrementMutableValue}>Increment Mutable Value</button>
      <p>Mutable Value (Last known, not live updated): {mutableValueRef.current}</p>
    </div>
  );
}

export default DOMInteractionComponent;
How it works: The `useRef` hook returns a mutable ref object whose `.current` property is initialized to the passed argument (`initialValue`). The returned ref object will persist for the full lifetime of the component. It's commonly used to access a DOM element directly (e.g., for focusing an input, playing media) or to store a mutable value that doesn't need to trigger a re-render when it changes, unlike state variables.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs