How to Use useRef Hook in React

Practical Example of Using useRef Hook in React

Alex zambrano
Enlear Academy

--

A quick explanation about the useRefhook in React.

This article provides a clear, practical explanation of the useRef hook in React. It explains a topic that sometimes causes a bit of confusion to developers, especially to React beginners.

The hook of useRef if you don’t have a clear idea of how this hook works? When do you have to use it? this article will be beneficial to you.

useRef Hook

The useRef is a function that can take an argument and return an object with a property current with its assigned value on it.

What If I want to change that value? Just write as follows val.current = “bar" and the value will change becauseuseRef is mutable, which means that it can be assigned, with any value, including nodes and DOM elements.

Now the value var.current has changed, but the component will still be the same this is because useRefdoesn’t re-render the component but let’s print the value of var.current.

The value has changed but is not reflected in the component. This is a handy feature because we can change the values of the component or properties in the DOM elements without re-rendering the component.

Access elements in the DOM

The most common way to use useRefis to access the DOM elements. The way to do this is to add a property ref in the DOM element.

By doing this, we can access the element with val.currentand change their properties in the same way that is getting an element of the document with getElementById.

In the code above, I add a button that on click event, triggers a function that changes the text to ‘Hola Mundo’ and the background to red.

It works perfectly and without re-render the element.

Conclusions

The useRefhook, as you may see, allows performing complex action in our component to improve the performance and interactivity of our application. I hope you have found this article useful. Thanks for reading it.

--

--