Is it bad practice to access HTML elements by ID in React TypeScript?

👍:-1

Yes,
It is not good practice to access dom elements directly through document API.

Because in react

  1. virtual dom is responsible for painting/ re-rendering the UI.

  2. State updation is the proper way to tell react to trigger re-render.

  3. The flow is state updation -> calculate differences -> find who over is using that state -> grab those components -> re-render only those components.

  4. virtual dom is the source of truth for react to render and update actual DOM.

Now, If you directly access some dom elements and do some operation on it, like updating, react will never know that some change has happened and it will basically break the flow of the react, in which case there will be no reason to use react.js

The flow would be accessing some dom element -> updating -> displaying.

The problem with this approach if react encounters that later what i have in virtual dom is not actual presentation in the actual dom, which will create mess.
That is the reason there is useRef hook to manipulate dom.

Leave a comment