Accessing DOM Elements

Learn how React uses a virtual DOM for efficient DOM updates and how refs serve as a means to directly work with DOM elements in the framework.

Direct DOM manipulation before React

Before a modern UI framework was introduced, to make a change to the screen, we worked directly with a DOM element. In the code below, a basic HTML body is combined with JavaScript to modify the content of an h1 element.

Press + to interact
<!-- HTML Body with an h1 element and a specified ID -->
<body>
<h1 id="title"></h1>
</body>
<!-- JavaScript script to set the text content of the h1 element with id 'title' -->
<script>
// Get the element by ID
const el = document.getElementById('title');
// Set the text content to "Hello World"
el.textContent = "Hello World";
</script>

The preceding HTML file defines an h1 element tagged with a specific id value. So we can use the id value to find the el element and make a change to its textContent. This is how a DOM element gets updated:

Press + to interact
HTML displaying the Hello World title
HTML displaying the Hello World title

React component abstraction

With React, we can achieve the preceding functionality by wrapping elements in a component, such as a function component:

const Title = () => {
// State to hold the title
const [title, setTitle] = useState("");
// useEffect to set the title to "Hello World" on component mount
useEffect(() => {
setTitle("Hello World");
}, []);
// Render the h1 element with the dynamically set title
return <h1>{title}</h1>;
}
Functional component using state and useEffect to set and display a title

The benefits of using this functional approach are that it provides an abstractionAbstraction refers to the process of hiding complex implementation details and presenting a simplified and high-level interface ...