The UseRef Hook.

Table of Contents

The basics

useRef(initialValue)

Hopefully this should be a quick one.

useRef is used for storing a value across renders, without causing a re-render when it is changed.

useState causes the component to re-render when it is changed.

useRef doesn't cause the component to re-render. Simple, really.

Things worth knowing

const numberRef = useRef(0);

numberRef.current = 5;
numberRef.current += 1;

// numberRef is now equal to 6

A real-world example

Let's say you want to create a React hook called useTimeout which invokes a callback after a specified delay. The hook should always invoke the latest callback it is given, without restarting the running timeout.

function useTimeout(delay, callback) {
const latestCallback = callback;
   latestCallback.current = callback;

useEffect(() => {
const timeoutId = setTimeout(() => {
latestCallback.current();
}, delay);

return () => clearTimeout(timeoutId);
}, [delay]);
}

Here, we're persisting latestCallback across renders, and reassigning its current property if a new callback function is received, without causing the existing timeout to be restarted.

Most commonly however, you'll see useRef attached to components/elements using the special ref attribute, e.g.:

const inputElementRef = useRef(null);

...

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

This enables us to access and perform operations on the underlying component by accessing inputElementRef.current, e.g.:

inputElementRef.current.focus();