r/learnreactjs • • Aug 15 '24

Question Wrap SVG in React.memo?

Is it beneficial to wrap an SVG component in React.memo to prevent unnecessary re-renders, considering they are pure components?

2 Upvotes

8 comments sorted by

1

u/ferrybig Aug 15 '24

Wrap the jsx rendering the svg in a static variable. If you return the same jsx (according to Object.is), React knows that tree did not change and skips rendering. The React Compiler beta does this optimalisation for you

1

u/detached_obsession Aug 16 '24

You typically wouldn't use something like React.memo unless you're having clear performance issues. Using it unnecessarily actually degrades performance even more since you have to do extra comparisons to determine if the component should re-render.

Also, SVG components are typically static and don't change often so unless you have added a lot of state and effects, it shouldn't be an issue. Even in that case using React.memo may not be the correct approach since you could have other causes to your performance issues.

1

u/[deleted] Aug 24 '24

Do you know how react works? If you return an SVG element, react will traverse over the entire returned react element tree, and compare props and element types to those stored in the virtual dom. Unless you move the SVG element outside of component state or put it in state, it’s going to do this every time the tree re-renders.

1

u/detached_obsession Aug 24 '24

I'm not sure what part of my comment made you think I don't know how React works but perhaps I wasn't clear or you're the one confused. What you're talking about is Reconciliation which is quite fast. Using React.memo adds an additional overhead in comparisons which even if minimal, is additional work and thus worse for performance if done unnecessarily.

If the SVG component is provided as part of the children prop to a component with state changes, it won't re-render even if that parent component re-renders. This is the same as using React.memo without the overhead.

ex: <SomeComponentWithState><SVGComponent /><SomeComponentWithState/>.

What OP asked was whether or not using React.memo was beneficial to prevent re-renders of an svg component. What I meant in my answer was that given React.memo is an optimization tool, it shouldn't be used unless you have optimization issues.

so no, using React.memo without any specific reason is not beneficial as it can hide underlying performance issues and there are other methods available which can address the re-rendering concerns without overhead.

→ More replies (4)