DEV Community

JckSmith
JckSmith

Posted on

So you want to use useRef...

So you found this fancy React hook that you want to try out! It's name is useRef, and the only problem is... you have never used it before! What is useRef and what does it do? Why would you ever use this in your code? These questions and many more can be answered pretty easily...

What is useRef? Well, useRef is a React hook that you can use to create a persisted mutable value! (AKA references or refs).

What is a reference? useRef accepts one argument as an initial value and returns a reference, a reference is an object having the property current. You can use reference.current to access the reference value, and reference.current = newValue updates the reference value.

Reference has 2 rules to remember

  1. The value of reference is persisted
  2. Updating a reference doesn't trigger a component re-rendering

Let's try it out!

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

  const handle = () => {
    countRef.current++;
    console.log(`Clicked ${countRef.current} times`);
  };
  console.log('I rendered!');
  return <button onClick={handle}>Click me</button>;
}
Enter fullscreen mode Exit fullscreen mode

const countRef = useRef(0) creates a reference countRef initialized with 0.

When the button is clicked , the handle function is invoked and the reference value is incremented, the reference is then logged in console.

Something to note, the message "I rendered!" only logged once at initial rendering, this shows how updating the reference value doesn't trigger component rerendering.

Now you may be wondering, what's the difference between references and state?

The Difference
Lets use the same code, but use useState instead to count the number of button clicks.

import { useState } from 'react';
function LogButtonClicks() {
  const [count, setCount] = useState(0);

  const handle = () => {
    const updatedCount = count + 1;
    console.log(`Clicked ${updatedCount} times`);
    setCount(updatedCount);
  };
  console.log('I rendered!');
  return <button onClick={handle}>Click me</button>;
}
Enter fullscreen mode Exit fullscreen mode

Now, each time you would click, the message, "I rendered!" is logged to console, meaning that each time state is updated, the component re-renders.

The main differences between references and state is that when you update a reference, it does not trigger re-rendering, while state does. And another difference would be that the reference update is synchronous (available right away) and state is asynchronous (available after re-rendering)

To sum it up, useRef creates references, calling const reference = useRef(initialValue) returns a special object named reference, which has the property current. You can use this property to read the value with reference.current, or update with reference.current = newValue. Between re-renderings, the value of reference persists. And finally, upon updating a reference, it does not trigger component re-rendering, unlike state.

While I didn't cover everything that useRef can do (Which is so much more!) I hope that this allows you to have a decent understanding on useRef!

Big thanks to Dmitri Pavlutin for the code snippets, and teaching me more about useRef! You can find his blog here!

Top comments (0)