useRef

useRef is a React Hook that gives you a mutable container whose value persists across renders without causing a re-render when it changes. It is most often used to access a DOM element directly.

React

useRef returns an object with a single .current property that you can read and write freely. Unlike state, changing .current does not trigger a re-render, making refs useful for values you want to remember but that shouldn't affect the UI.

The most common use is grabbing a real DOM node: attach the ref to an element with the ref attribute, and React sets ref.current to that element. You can then call methods on it, such as .focus().

Syntax

const myRef = useRef(initialValue);

Examples

JSX — Clicking the button moves the keyboard cursor into the text input by calling focus() on the referenced DOM node.

import { useRef } from "react";

function SearchBox() {
  const inputRef = useRef(null);
  return (
    <div>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </div>
  );
}

Learn it in a lesson

See also

Back to the Dictionary