Today I learned - React refs

kethmars - Jan 30 '20 - - Dev Community

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):
createRef example

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.

useRef example

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:
https://i.giphy.com/media/LndDkp00MVrF9ECX55/giphy.gif

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player