Skip to content

Understanding the useRef Hook in React

In this article, we will learn how to use the useRef hook in React.

What is the useRef Hook?

The useRef hook is used to create a mutable reference that persists across re-renders of the component. It is similar to the ref attribute in class components.

In case of Vanilla JS, we can use document.querySelector('#myElement') to get the reference of an element. But in React, we can use the useRef hook to achieve the same functionality with a better performance.

When to Use the useRef Hook?

Example with reference to a DOM element

Let’s see an example of how to use the useRef hook to store a reference to a DOM element.

import React, { useRef } from "react";

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

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

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

export default App;

In this example, we create a reference to the input element using the useRef hook. When the button is clicked, the handleClick function is called, which focuses the input element using the inputRef.current.focus() method.

Example with avoiding re-renders

Let’s see an example of how to use the useRef hook to store a mutable value that doesn’t trigger re-renders.

import React, { useState, useRef } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  const countRef = useRef(0);

  const increment = () => {
    setCount(count + 1);
    countRef.current = countRef.current + 1;
  };

  return (
    <div>
      <p>Count: {count}</p>
      <p>Count (ref): {countRef.current}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;

In this example, we use the useRef hook to store the count value without triggering re-renders.

The countRef.current value is updated directly without causing the component to re-render.

Summary