DEV Community

kethmars
kethmars

Posted on

Today I learned - React refs

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

Top comments (3)

Collapse
 
jivkojelev91 profile image
JivkoJelev91

Nice, i recommend you, don't use it.

Collapse
 
kethmars profile image
kethmars • Edited

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.

Collapse
 
dance2die profile image
Sung M. Kim • Edited

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.