Accessing DOM Elements
Explore how to access and manage DOM elements in React using the useRef hook. Understand React’s abstraction of the DOM, challenges of direct DOM manipulation within components, and how useRef provides a safe, lifecycle-aware way to interact with element instances.
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.
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:
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 titleconst [title, setTitle] = useState("");// useEffect to set the title to "Hello World" on component mountuseEffect(() => {setTitle("Hello World");}, []);// Render the h1 element with the dynamically set titlereturn <h1>{title}</h1>;}
The benefits of using this functional approach are that it provides an