React useRef Hook

The ref is used to return a reference to a particular element. useRefs has its advantages but should be generally avoided, they can be useful in DOM manipulations, measurements, and adding methods.

To understand the usefulness of useRefs, we write a function that calculates the amount of times the name state was re-rendered using useEffect hook. As you might notice on the page, the count shows a count of one because useEffect hook renders before the component is mounted and on each update. We can easily avoid this by using useRef to maintain the state of the numOfRenders state. useRef has a current property equal to the value of the state. This current property only updates when there is a subsequent update after the first render.

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

export default function App() {
  const [name, setName] = useState("");
  const [numOfRenders, setNumOfRenders] = useState(0);

  useEffect(() => {
    setNumOfRenders((prevStateCount) => prevStateCount + 1);
  });

  return (
    <div>
      <input
        type="text"
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <div>My name is {name}</div>
      <div>Number of renders :{numOfRenders} </div>
    </div>
  );
}

So the example now looks like this:

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

export default function App() {
  const [name, setName] = useState("");
  const numOfRenders = useRef(1);

  useEffect(() => {
    numOfRenders.current = numOfRenders.current + 1
  });

  return (
    <div>
      <input
        type="text"
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <div>My name is {name}</div>
      <div>Number of renders:{numOfRenders.current} </div>
    </div>
  );
}

Reference/Focus on an element

Now let’s look at actually giving a reference to an input element by focusing on it after a button click:

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

export default function App() {
  const [name, setName] = useState("");
  const inputRef = useRef();
  function Focus() {
    inputRef.current.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={inputRef}
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <div>My name is {name}</div>
      <button onClick={Focus}>Focus</button>
    </div>
  );
}

Result:

We set a variable of inputRef to useRef hook and pass it to the function ‘Focus’ which allows us to use the current object property of focus() on our input field. Do not use useRefs to manage your form data, use useState instead as useRefs do not update the state of your components.