DEV Community

Cover image for Mutable values with React.useRef()

Mutable values with React.useRef()

vineetk13 profile image Vineet K ・2 min read

React.useRef() hook is basically used to refer to DOM elements and also to create mutable values persisted between component re-rendering.

The first use case seems pretty straightforward but, what about the second one.!? Let's look at what it is and how does it work.

Firstly, what is a Mutable?

It can be referred to as a type of variable containing mutable values i.e., values that can be changed in same memory space they were created.

In JavaScript, only arrays and objects are mutable.

useRef() in action

React.useRef() takes an initial value as it's only arguement and returns a special object called reference. It has a single property named current which holds the reference value.

const reference = React.useRef(initialValue);
console.log(reference);   // { current : <referenceValue> }
Enter fullscreen mode Exit fullscreen mode

The reference object here is mutable which means we can access the reference value using reference.current and update it by assigning reference.current to a new value or variable. Huh! what's so special about this?🤷‍♂️

The speciality

There are two important behaviours to remember about useRef() references:

  1. The reference value stays the same (persists) between component re-renders.
  2. Updating a reference value does not re-render the component.

Example - Logging button clicks

import { useRef } from 'react';
const LogButtonClicks = () => {
    const countRef = useRef(0);

    const handleClick = () => {
        console.log(`${countRef.current} button clicks`);

    console.log("Component rendered");

    return (
        <button onClick={handleClick}>Click me!</button>
Enter fullscreen mode Exit fullscreen mode

Here const countRef = useRef(0) creates a reference countRef initialized to 0. We use this reference object to store the number of clicks on a button. On clicking the button, the reference value is updated and logged to the console. As you might have noticed in your console that "Component rendered" is logged only once (during the initial render) which means that the button clicks, more precisely, the reference value updates do not trigger component re-renders.

This further leads us to think about the difference between state and references.

Difference between state and references

  1. Updating state does trigger component re-rendering but updating a reference does not.
  2. The state update is asynchronous (state variable is updated after re-rendering - refer this for more detailed explanation), while the reference update is synchronous.

No rule of thumb

useRefs are just escape hatches in the framework and are not meant to be used unless necessarily required. However, they can be used to store any infrastructural data but never to store presentational data. Also do mind them while accessing DOM nodes.

Thank you ❤

Connect with me on twitter and let's explore the web world together.

Discussion (1)

wasitshafi profile image
Wasit Shafi

Thank you for such a nice article

Forem Open with the Forem app