How to Persist Values Between Re-Renders Using React useRef()?

In React, a component can re-render multiple times based on changes to reactive values (such as values passed as props to the component, declared as state, or other variables inside component's function body). When a component re-renders, its internal state is reset, and any local variables inside its function body are also re-initialized.

However, certain values can persist across re-renders — i.e., they are not reset or re-initialized when the component re-renders. One way to create such values is to use the useRef() hook, which is specifically designed to create a reference that persists across re-renders. When you use useRef(), it creates a mutable "ref" object that can hold any value and does not trigger a re-render when it's updated. This means that the value you store in a ref persists across re-renders, allowing you to retain/maintain/access it without having to recalculate or re-initialize it every time the component re-renders.

Please note that useRef() should not be overused and should be used in situations where it provides a clear benefit, such as for referencing DOM elements or other expensive computations.

For example, let's suppose you have a component that needs to store a reference to an HTML element that's generated by the component. You can use useRef() to do so, in the following way:

import React, { useRef } from 'react';

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

  function handleClick() {
    myRef.current.style.color = 'blue';
  }

  return (
    <div>
      <h1 ref={myRef}>Hello world!</h1>
      <button onClick={handleClick}>Change color</button>
    </div>
  );
}

Here, the useRef() hook is used to create a ref called "myRef", which is attached to the <h1> HTML element. In this way, you have access to the HTML element without having to re-query the DOM every time the component re-renders (for example, when a reactive value triggers an update).

Therefore, each time the component re-renders, myRef.current will not have to traverse through the DOM tree hierarchy to access the <h1> element. Instead, it will have the reference to it, which isn't reset, as it persists across re-renders. Using this stored reference of the HTML element, you can manipulate it (such as by changing it's color, etc.) and have it reflected in the document, without triggering a re-render of the component.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.