Today I learned is a series where I share a short summary of one thing I learned during the day. The idea is to show what resources I used and give my own short explanation to things.
Regarding FE libraries for building UI, my go-to library has been Vue. Lately, I've also started to use React because well...it's the most-used FE library for the aforementioned purpose(NPM depended).
Yesterday, I reviewed a PR that used useRef
hook, which I didn't know of before. That's why I started to look into it.
What are refs in React?
Refs provide a way to access DOM nodes or React elements created in the render method.
Usually, refs are used to manipulate the DOM node state(focus, active etc).
An example of using ref (from https://reactjs.org/docs/refs-and-the-dom.html):
this.textInput.current
refers to the DOM node, thus we can call out the .focus() method on it.
It's important to remember that each time the component rerenders, a new ref object is created.
Cool,but I've also seen useRef?
With React hooks, useRef was introduced.
Difference?
"Well, the difference is that createRef will return a new ref on every render while useRef will return the same ref each time." by TrinhDinhHuy in DevTo
In his Article Introduction to useRef Hook, TrinhDinhHuy has created an awesome animation about the differences between createRef
and useRef
:
Also, remember that inputEl.current
gotten from React.useRef() is actually a mutable property that you can set to whatever you want and it won't change on rerendering. So basically, you can use React.useRef as instance variables (Instance variables in React).
Resources I used to learn
- ReactJS doc - refs and the dom
- ReactJS doc - useRef
- Introduction to useRef Hook - a post by fellow dev.to member TrinhDinhHuy. Really helpful with great examples and animations. So good that I actually borrowed his animation.
Top comments (3)
Nice, i recommend you, don't use it.
Hey Jivko! Thanks for the comment.
Can you elaborate please :) ?
I guess that refs can easily be misused because you shouldn't need DOM access too much in libraries that work like React. But there are times when it makes sense. For example combination with event.target.
It's literally an "escape hatch" as the React doc the @kethmars linked. (translates to, "don't abuse it" 😉)
One instance you can use is when you want to integrate JS library w/o React version.