From the course: Master React 19 and Next.js 16 with Hands-On Projects and Real-World Applications

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Best practices for DOM manipulation with refs

Best practices for DOM manipulation with refs

In this session, we'll explore best practices for DOM manipulation in React using refs. You'll learn why directly mutating the DOM can cause problems, and how refs provide a safer alternative for specific tasks. Remember, mixing state-driven rendering with direct DOM manipulation often leads to conflicts and bugs, because React loses track of changes. Refs are excellent for non-destructive actions like focusing or scrolling, as long as you avoid interfering with React's state management. This will all make sense by the end of this session. Let's start with our basic React component. Now I am introducing state management using the UseState hook. This adds the items array to hold our fruit list and setItems function to update that array. You will now be able to dynamically change the content of our application. Now it is time to enhance the rendering. I've replaced the simple H1 with a div structure to prepare for adding our fruit list. We are building the structure to hold our dynamic…

Contents