2 min read
Tweaking SVGs works best with useRef

This way we get less bug-suprises

When we are working with SVGs in a React app. We get two options to render and update the SVGs :

  1. Either we put all the elements (rects, paths, lines etc) inside the JSX block
  2. 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 :

  1. 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.

  2. 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.

  3. 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.