Sobes.tech
Middle+

Why is useRef needed? What are its applications?

sobes.tech AI

Answer from AI

useRef in React is a hook that allows creating a mutable object with a .current field, which persists between component renders. Main uses:

  • Storing DOM elements: you can get a reference to an element to manage focus, measure sizes, or call methods directly.
  • Storing mutable values: keep values that do not affect rerenders, such as timers, identifiers, previous prop or state values.
  • Imitating instance variables: in functional components, useRef replaces class properties for storing data between renders.

Example of usage for DOM access:

import React, { useRef } from 'react';

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

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

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

Thus, useRef is a convenient tool for storing data that does not trigger re-renders and for working with the DOM.

Why is useRef needed? What are its applications… - sobes.tech