Introduction
In order to interact with HTML elements, we often use JavaScript's getElementById
or React's useRef
. But how do these methods differ and when should each be used? This post will explain the differences between getElementById
and useRef
in a way that even beginners can understand.
What is getElementById?
getElementById
is a basic JavaScript function used to retrieve HTML elements with a specific ID attribute.
Below is a simple example of retrieving the text content from an HTML element.
<div id="myDiv">Hello, World!</div>
let div = document.getElementById('myDiv');
console.log(div.textContent); // "Hello, World!" will be logged.
In this code, we use the getElementById
function to get the <div>
element with the ID "myDiv" and log its text content to the console.
Advantages and Disadvantages of getElementById
Advantages
-
getElementById
is pure JavaScript, so it can be used without depending on any particular library or framework. - Because the ID attribute is unique, you can directly retrieve the specified element.
Disadvantages
- Frequently using
getElementById
within frameworks like React can take you away from the framework's "declarative" patterns. - Frequently using
getElementById
increases direct DOM manipulation, which may complicate code management.
What is useRef?
On the other hand, useRef
is a React Hook used to refer to specific elements within a React component.
Below is an example of logging the text content of a specific element to the console when a button is clicked.
import React, { useRef } from 'react';
function MyComponent() {
const myDivRef = useRef(null);
const handleClick = () => {
console.log(myDivRef.current.textContent);
}
return (
<div>
<div ref={myDivRef}>Hello, World!</div>
<button onClick={handleClick}>Display Text</button>
</div>
);
}
export default MyComponent;
In this code, we use the useRef
Hook to create a reference to the <div>
element and save it in myDivRef
. Then, when the button is clicked, we use that reference to log the <div>
's text content to the console.
Advantages and Disadvantages of useRef
Advantages
-
useRef
is part of React's Hooks, making it suitable for use within React components. -
useRef
is used to hold references, so once set, its value will persist even through re-rendering.
Disadvantages
-
useRef
is a concept specific to React, so its usage is limited to a React context. - While useRef is primarily used to refer to DOM elements, using it for other purposes (like holding values) may make the code harder to understand.
Conclusion
Understanding the differences between getElementById
and useRef
enables you to choose the right method based on the specific situation, requirements, and the tech stack you're using (whether it's pure JavaScript or a framework like React). Understand each method's characteristics and choose the right one for efficient development.
Thank you for reading. I hope this post helps you in your learning journey. Your reactions and comments are always welcome!
Top comments (5)
Great explanation!!
well explained, though you didn't mention the main point:
getElementById directly interacts with the browser's DOM, bypassing React's virtual DOM mechanism. It can lead to inconsistencies and bugs, especially since React is not aware of these changes. React might overwrite your changes during its next render cycle.
With this I have take toe dip into React I guess.
Nice lesson.
My question now is :can I use document.getElemenByID()
in React?;
I have never come across useRef in JS though.
//I think using the useState hook to refer to the element you want is a best practice to use in //react.
const [elmenet,setElement] = useState(document.getElementById("element_id"));
//then you can use the (element) const as you wish
or you can also use it normally in any function or any hook (like useEffect) if you want.
ex:
useEffect(()=>{
const myELe = document.getElementById("element_id");
// your code//
})
Thanks, easy explanation. 😁