The useRef() hook- a Practical use case

SAAD ZAKAULLAH AHMAD
2 min readAug 28, 2022

When to use useRef over useState hook and how to use one useRef hook for multiple elements?

useRef is one of the “not used where it should be” kinds of hook in React. People generally learn about using this hook while preparing for the interviews, and I know it because I was one of them too.
I did all of the work that could be done with the useRef by useState hook until I had a fantastic tech round with a CTO.
For example, I used a state to track the changes in input text elements even though I didn’t need their updated values on every keystroke. All I needed was to have a final value from those elements, and send those values to the API, say as a query parameter, upon clicking a button.
Let me explain by showing you a code:

The problem with this approach is- even if I want the values of input and password only after pressing the login button, I am still rendering my component again and again on every keystroke since I have put both of their values in useState. This might not be an issue in small apps, but this may be a concern in production-level code.
So, how do we solve this problem? How do we prevent unnecessary re-renders while getting the latest value in those input boxes so their values may be sent to the backend? Well, that’s where useRef comes into the picture, my friends.

See code:

Here, we can clearly see that attaching the inputs to the refs prevented unnecessary re-renders and reduced the number of lines of code.

The cherry on the top

Knowing all this, one might wonder, what if we have multiple inputs? Do we need to create separate refs for each of them? The problem was solved by putting values inside an object, so we may need only one state value while using useState. But what about useRef?
Well, here’s the solution:

The above cases are of course only a few of the many other use cases of the useRef hook.

Well, that’s it for now. I hope this blog added a new layer of understanding of the useRef hook. Drop a 👏 if you liked it. And until next time, my friends, be legendary.

--

--

SAAD ZAKAULLAH AHMAD

A web developer, mechanical engineer and an eternal learner.