Have you heard about Hack Frontend Community?Join us on Telegram!
Practice React Problems

useRef in React: DOM Access and Mutable Values

useRef is a hook in React that allows storing references to DOM elements or values that don't cause component re-render when changed. This can be useful for accessing DOM elements or storing values between renders.

How Does useRef Work?

  • References to DOM elements. useRef can be used to get direct access to DOM elements, for example, to focus on input field or measure element sizes.

  • Storing values between renders. useRef stores value that doesn't cause component re-render when changed. This is useful when you need to store data that shouldn't be part of component state but should persist between renders.

const myRef = useRef(initialValue);
  • initialValue — initial reference value. It can be null or any other value you need to store.

  • myRef.current — object that stores current value. For DOM element references, myRef.current will reference the element itself.

useRef Usage Example for DOM Work

import { useRef } from "react";

function FocusInput() {
  const inputRef = useRef(null);

  const focusInput = () => {
    inputRef.current.focus(); // Focus on input field
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus on input</button>
    </div>
  );
}

In this example:

  • inputRef is created using useRef and passed to input field's ref attribute.
  • When user clicks button, focusInput function is called, which focuses on input field using inputRef.current.focus().

useRef Usage Example for Storing Values

import { useRef } from "react";

function Timer() {
  const countRef = useRef(0);

  const increment = () => {
    countRef.current += 1;
    console.log(countRef.current); // Prints number of updates
  };

  return (
    <div>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

In this example:

  • countRef is used to store counter value between renders.
  • countRef.current value can be changed directly, and this won't cause component re-render.

When to Use useRef?

  • DOM element access. If you need to work with DOM (e.g., focusing, measurements or animations), use useRef to get element references.
  • Storing data between renders. If you need to store data that shouldn't trigger re-render, use useRef. For example, to store current timer state or track previous values.

Using useRef:

useRef allows storing data or element references between renders without causing unnecessary re-renders, making it ideal tool for DOM work and storing state that doesn't affect rendering.

Practice React Problems

By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.