9

Some time ago, refs were introduced in Lightning Web Components.

Now you can use refs to access elements in shadow DOM and light DOM. Refs locate DOM elements without a selector and only query elements contained in a specified template. Previously, you could only use querySelector() to locate specific DOM elements.

We have two possibilities to get HTML elements in JavaScript:

  • refs
  • querySelector

I found in Is there any advantage of using ref over selecting element using document.querySelector? that refs are much more efficient. Refs have some limitations, like: If you place lwc:ref in a for:each or iterator: loop, the template compiler throws an error.

My questions are:

  1. Should we mostly use refs instead of querySelector?
  2. What are the use cases for refs and what are the use cases for querySelector?

I didn't find any simple rules in Access Elements the Component Owns that state when to use which method.

Reference:

1 Answer 1

5

Should we mostly use refs instead of querySelector?

Yes. Consider two analogies: (a) you walk into a store and walk up and down every aisle, considering every product, until you find the one you want, or (b) you ask a store employee to take you directly to the product you need. That's the relative difference in performance, where (a) may obviously take a very long time (O(n/2) on average), while (b) is instant and in fixed time (e.g. O(1)).

What are the use cases for refs and what are the use cases for querySelector?

refs should be used all the time, if appropriate. If you're trying to get a list of elements from a template iterator, you'd use querySelectorAll. In all cases where the elements are in your template, refs are the way to go. The only time you "want" to use querySelector is when a ref isn't available, perhaps because the element is inside a lwc:dom="manual" region (e.g. rendered by a third party library), or you need to select by an attribute.


With all that said, it is likely not worth refactoring. Most components are small enough, fast enough, and call querySelector so infrequently that the performance gains would go unnoticed. Certainly prefer to use them for new code, and maybe update existing code as you fix bugs or add new features, but don't make it an entire side project unto itself. Aside from some contrived examples, such as implementing some simulation that needs to run as fast as possible, switching to refs just for the sake of it isn't likely worth it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .