How to Use the React useRef Hook



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

Using the useRef hook

The React useRef hook is a built-in hook that provides a way to create and manage a mutable reference to an object that persists across re-renders of a component. It’s a powerful tool that can be used to access and manipulate the DOM elements or other values within a component.

To use the useRef hook, you need to import it from the ‘react’ package like this:

import React, { useRef } from 'react';

Then, you can declare a variable using the useRef hook, like this:

const refVariable = useRef(initialValue);

The initialValue is the initial value of the ref, and it can be any JavaScript value. The refVariable is a mutable object that can be used to store and update the reference to the DOM element or any other value.

Here are some common use cases of the useRef hook:

Accessing DOM elements

You can use the useRef hook to access the DOM elements within a component. For example, you can use it to get a reference to an input field and set its value programmatically:

function MyComponent() {
  const inputRef = useRef(null);
  const handleClick = () => {
    inputRef.current.value = 'Hello world';

  return (
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Set Value</button>

Storing previous values

You can use the useRef hook to store the previous values of a prop or state variable. This is useful when you need to compare the current and previous values in a useEffect hook:

function MyComponent(props) {
  const prevPropsRef = useRef(props);

  useEffect(() => {
    if (prevPropsRef.current !== props) {
      console.log('Props changed!');
      prevPropsRef.current = props;

  // ...

Caching expensive computations

You can use the useRef hook to cache the result of an expensive computation. This is useful when you need to re-use the result multiple times within a component:

function MyComponent() {
  const expensiveResultRef = useRef(null);

  if (!expensiveResultRef.current) {
    expensiveResultRef.current = computeExpensiveResult();

  // use expensiveResultRef.current ...

  // ...