Angelos Orfanakos

Wrapping my head around React's useRef

While learning about React Hooks, I had a hard time understanding the case for useRef. Then I ran into this:

useRef(initialValue) is essentially useState({ current: initialValue })[0]. useState returns an array where the first element is the state and the second is its setter. [0] means the setter is discarded.

This is useful in cases where we want to persist state between renders and modify it without triggering a render (contrary to useState). It works because the state (an object) is modified directly (i.e. myRef.current = 42) and not through its setter (which triggers the render).

That’s also why the returned state is { current: initialValue } (an object) and not just initialValue (a primitive value). Without a setter, it’s not possible to modify it:

// State is a primitive value
let name = useState('Angelos')[0]; // Discard setter method
// name === 'Angelos'
name = 'John'; // This just modifies the local variable "name"

// State is a reference to an object
const nameRef = useState({ current: 'Angelos' })[0]; // Discard setter method
// nameRef.current === 'Angelos'
nameRef.current = 'John'; // This modifies the object's "current" property