An easy guide to understanding react useRef hook

An easy guide to understanding react useRef hook

Prerequisites

  • Familiarity with react

Note - You do not need to be an expert in react but you must have seen some react code before reading this article.

Introduction

In this blog, we will cover the useRef hook which is commonly used to create a mutable reference value and to manipulate DOM.

What exactly is the useRef hook and how to use it?

Like useState hook useRef hook is also used to remember some information in a component but unlike useState it is mutable and any change in its value does not cause any re-renders.

How to use it?

Let's say we want to keep track of the number of times our component gets rendered. Simply, creating a state and incrementing it inside a useEffect hook will not work here and will lead to infinite renders.

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  const [numOfRenders, setNumOfRenders] = useState(0);

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

  const handleCount = () => {
    setCount((prev) => prev + 1);
  };

  return (
    <div className="App">
      <p>Number of times component gets rendered - {numOfRenders}</p>

      <button onClick={handleCount}>Increment count</button>
      <p>Count is {count}</p>
    </div>
  );
}

Check the below code sandbox to understand the problem.

Number of render exercise first version

This is happening because every time we are updating the numOfRenders state inside useEffect hook, it is also causing a re-render (since a component re-renders every time its state gets changed) which is leading to an infinite loop. So, how do we solve it? We will use useRef hook to solve the above issue. Why? because as discussed above useRef hook does not cause re-renders when its value gets changed and like useState hook its value also persists between re-renders.

To use useRef hook we will first import it from the react library just like we do when using any other built-in react hooks.

import { useRef } from "react"

now call useRef hook inside your component and give it some initial value.

const ref = useRef(0)

Note - I have given 0 as the initial value but it can be anything an array, object, or even function.

useRef hook returns an object which has a special property called current, this current property holds the value of the reference and is also used to update the current value. In our scenario, the initial value of ref will be.

{current: 0}

Now, we can update the value of our reference using this current property.

ref.current = 5

the above code will set the value of ref to 5.

Keeping this in mind now calculate the number of times our component re-renders using useRef.

Check the code sandbox below.

Number of re-renders exercise

Now, it will not lead to infinite re-renders as updating the ref value does not re-render the component.

Manipulating DOM with useRef hook

Another use case of the useRef hook is, that it is used to manipulate DOM nodes. To manipulate the DOM node we first declare useRef inside our component as we have discussed in the previous section.

const inputRef = useRef(null)

We then pass it to the DOM node we want to manipulate and assign it to the ref attribute in the targeted element/component.

<input type="text" ref={inputRef}/>

now if we will console our inputRef you will see the current property holds our input element and it will look as below.

{ current: <input type="text"></input> }

Now, we can manipulate this DOM node using the built-in browser APIs.

import { useRef } from "react";
import "./styles.css";

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

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

  return (
    <div className="App">
      <input type="text" ref={inputRef} />

      <button onClick={handleFoucs}>focus input</button>
    </div>
  );
}

See, the below code sandbox to check how we can use useRef to focus on the input element that we just created.

Foucs input element demo

When to use useRef hook?

useRef is an escape hatch so it should be used sparingly. Most times it is used to manipulate DOM elements to manage focus, scroll, or call browser APIs that React directly does not expose. Other times it is used in storing timer Ids.

Summary

  • Like useState hook useRef hook is also used to remember some information in a component but unlike useState, it does not cause any re-renders.

  • useRef hook is most commonly used in manipulating DOM nodes.

  • We should use useRef hook sparingly and should not modify DOM nodes managed by React because that can lead to unusual visual results or even crash your web app.

Thanks for reading it till the end. Do leave your feedback in the comment section below.