When we are working with SVGs in a React app. We get two options to render and update the SVGs :
- Either we put all the elements (rects, paths, lines etc) inside the JSX block
- Or we just have a parent SVG element and then use some library like D3 to append and update elements into it
I personally prefer the second one. And from the work of other developers in this community, I can also see that many of us like it that way. So here is why using useRef adds more value into the process :
-
Ensuring DOM Element Existence: In React, components are rendered conditionally based on state or props. If the DOM element you want to reference doesn’t exist yet, accessing it directly would result in an error. useRef creates a persistent reference to the DOM element, even if it’s not currently in the DOM. This allows you to safely access it later when it’s rendered.
-
Avoiding Re-renders: When we update something in SVG elements, then our app might re-render because of React’s reconciliation process, which is definately a behviour we want. By using useRef to store a reference to the DOM element, you can avoid triggering re-renders of the entire component when only SVG operations need to be performed.
-
Direct Manipulation of DOM Elements: Thee visulisation libaries often requires direct access to DOM elements to perform its operations, such as selecting elements, setting attributes, and applying styles. useRef provides a way to get a direct reference to the DOM element, enabling you to pass it to abstarct library functions.