PT-BR EN
Blog

How to Use useRef

2 min read
How to Use useRef

What is useRef

Now imagine you are a construction inspector and you have to write down on a wall, with chalk, everything that gets done on the site. But writing on the wall is itself an act too. You are a very logical person and conclude that you must also write down that you wrote that on the wall, and you write down again that you made the note, and this creates a loop in the state.

How do you prevent a value update from causing a new render of the component?

useRef solves this problem!

Reference

A ref is an object from useRef that keeps a property called current, where you can store a value. A ref can also point to a DOM element, allowing you to call specific methods and access and manipulate element properties in the HTML, which is probably the biggest use for this hook.

Updating this ref does not cause reactivity and does not re-render the component. Since it does not cause a new render of the component, we should not use useRef for visual reactivity. For that, there is useState.

Parameters

useRef takes a single parameter, the initial value of the ref.

const myRef = useRef(initialValue);

Return value

It returns an object with the current property, where we can access and modify that value.

Examples

useRef does not cause a new render, unlike useState

Counting how many times a component renders

Reading and manipulating DOM data to drag an element