'React using refs instead of #id selector
I have come across a few different articles saying refs are the 'react way' of doing things in place of the #id selector. I'm not certain why. What is the explanation for using refs instead of #id?
import {useRef} from 'react';
function Home() {
const exampleRef = useRef(null)
return (
<div ref={exampleRef}> Hello world </div>
)
}
export default Home;
vs.
function Home() {
return (
<div id='example'> Hello world </div>
)
}
Solution 1:[1]
I can think of two main reasons:
You can skip the
Document.getElementById()
call and directly accessexampleRef.current
The
current
property of theuseRef
object is fully mutable and can be assigned any arbitrary value. Mutating it does not trigger full component re-renders (like calling the setter function from auseState
hook would), which is sometimes necessary for performance.
Sometimes w3schools articles are lacking in substance, but their useRef
article has some good examples of simple use cases.
Solution 2:[2]
React useRef
returns a object which remains same reference between re-renders with a current
property which is mutable.
The reason ref
is preferred than getElementById
is that
It is easy to access , no need to define an id to your DOM node just for accessing it.
Unlike
ids
refs are unique, you don't need to worry about it while declaring it. if you have more than one DOM node with sameid
in the document,getElementById
might not return the element you expect.
You can read more about refs in React's beta docs
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | fowl- |
Solution 2 | Shan |