JAVASCRIPT

Interact with DOM or Store Mutable Values with useRef Hook

Explore React's useRef hook to directly interact with DOM elements or store mutable values that persist across renders without causing re-renders.

import React, { useRef, useEffect } from 'react';

function FocusInput() {
  const inputRef = useRef(null);
  const renderCount = useRef(0); // Persistent mutable value

  useEffect(() => {
    // Direct DOM manipulation: focus the input field after render
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []); // Run once on mount

  useEffect(() => {
    renderCount.current = renderCount.current + 1;
    console.log('Component rendered:', renderCount.current, 'times');
  }); // Runs on every render

  return (
    <div>
      <label htmlFor="myInput">Enter your name:</label>
      <input id="myInput" type="text" ref={inputRef} />
      <p>Check console for render count.</p>
    </div>
  );
}

export default FocusInput;
How it works: The `useRef` hook allows you to create a mutable `ref` object whose `.current` property can hold any value. It's primarily used for two purposes: 1) Accessing DOM nodes directly (e.g., focusing an input, measuring dimensions), and 2) Storing a mutable value that persists across component re-renders without triggering a re-render itself. Unlike state variables, updating a `ref.current` value does not cause the component to re-render.

Need help integrating this into your project?

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

Hire DigitalCodeLabs