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.
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.
With React hooks, useRef was introduced.
"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
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).