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...
For further actions, you may consider blocking this person and/or reporting abuse
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! π€
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 ofisFetching
orhasMounted
boolean that you need to keep track of.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.
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-...
Interesting, I'll give that a read. Thanks!