Paul Gege
Paul Gege

Reputation: 31

DOM vs Refs in React

What is the difference between using DOM vs Refs in React? I understand that we can use regular javascript DOM node selectors to target specific elements in react because react is javascript anyways, but you can also use refs to do the same thing. What are the benefits/disadvantages of using one vs the other?

Upvotes: 3

Views: 781

Answers (3)

Denny John
Denny John

Reputation: 464

It’s because of React, JSX, and the lifecycle pipeline. When you hear people refer to the React ecosystem, these are parts of that ecosystem. Refs make working within that ecosystem a little more smooth.

In React, you typically interact with elements when there is a data change, which causes our typical lifecycle events like mounting and unmounting.

DOM Selectors happens outside of that lifecycle, making what it returns unreliable, while refs happen within it. This ensures the object returned by the ref is an accurate representation of the current state of the virtual DOM.

More Info

Upvotes: 0

TBouder
TBouder

Reputation: 2719

Refs provide a way to access DOM nodes or React elements created in the render method. You can check the documentation for more informations.

Upvotes: 0

Muhammad Haseeb
Muhammad Haseeb

Reputation: 1341

Its just a react way of accessing DOM nodes or React elements.

Upvotes: 2

Related Questions