DEV Community

Cover image for Storing values with the useRef hook

Storing values with the useRef hook

Emma Goto πŸ™ on February 20, 2020

React's useRef hook is used to store references to DOM elements. But did you know you can store and update values with useRef? Storing el...
Collapse
 
caiangums profile image
IlΓͺ Caian

Hey there! Nice written article!

Personally I can't see a real use-case of this except for counting re-renders and if you could provide one or two it'll be nice πŸ˜„

As ReactJS is leading to a more Functional approach with Immutability it is nice doesn't have side effects and just use variables inside Component State (using the useState() hook), and for Application State is common the usage of libs like Redux.

One good reference for this is this article as Updating a ref value is a side effect and side effects should be avoided or even dealt inside the useEffect() hook.

The main point I'm saying here is: you can use useRef() for storing values but you shouldn't.

Again, thanks for sharing some knowledge with us! πŸ€—

Collapse
 
emma profile image
Emma Goto πŸ™

Hi! Good point on keeping their usages inside of useEffect.

Storing variables in useState will be fine most of the time, but if you're in a situation where you're concerned about unnecessary re-renders impacting performance, this can be a useful way of getting around that. A real use-case might be if you had some sort of isFetching or hasMounted boolean that you need to keep track of.

Collapse
 
nickksm profile image
nickksm • Edited

I was just building an image slider/swipe like Instagram, using transform translateX css to slide the image. I needed to store the "evt.touches[0].clientX" value (current touch position), and later use that value in the transform translateX.

Every time the finger slides, I needed to re-update the value so I'll know which way the user is sliding. Storing this value in a state causes a LOT of unnecessary re-renders. Using useRef to store values without re-render was exactly what I needed.

Collapse
 
kildareflare profile image
Rich Field

Dan Abramaov has a great post on using this feature of hooks to make setInterval declarative.
The hook is used to store a reference to a callback.
overreacted.io/making-setinterval-...

Collapse
 
emma profile image
Emma Goto πŸ™

Interesting, I'll give that a read. Thanks!