Home > Software design >  React using refs instead of #id selector
React using refs instead of #id selector

Time:05-08

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>
  )
}

CodePudding user response:

I can think of two main reasons:

  1. You can skip the Document.getElementById() call and directly access exampleRef.current

  2. The current property of the useRef 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 a useState 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.

CodePudding user response:

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 same id in the document, getElementById might not return the element you expect.

You can read more about refs in React's beta docs

  • Related