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

View all comments

Show parent comment

1

u/detached_obsession Aug 24 '24

Even if a parent component re-renders too often to the point of causing issues, then the cause isn't the SVG component, it's something else that should be optimized. If in fact the SVG is large and complex and there are noticeable performance issues then I agree with using React.memo or other memoization techniques on that component.

My point still stands that it should depend and it shouldn't be done without first doing some kind of performance measurements.

1

u/[deleted] Aug 25 '24

Even if a parent component re-renders too often to the point of causing issues

It doesn't matter if it's causing issues. Everyone should attempt to write performant code.

it's something else that should be optimized

Let's say you have a controlled input component that is adorned with an error or checkmark icon, depending on whether or not there is an error in state. The input component is going to re-render every single time the value changes. Why wouldn't you memoize the svg?

1

u/detached_obsession Aug 26 '24

It doesn't matter if it's causing issues. Everyone should attempt to write performant code.

Of course it matters if it's causing issues. If you use React.memo on an SVG component and that component takes in a prop that changes constantly, your memoization isn't doing anything to help. Finding root causes and addressing them is far more valuable than doing preemptive optimizations.

Now I'm not saying you should never memoize, I'm saying it should be used to address specific issues.

Let's say you have a controlled input component that is adorned with an error or checkmark icon, depending on whether or not there is an error in state. The input component is going to re-render every single time the value changes. Why wouldn't you memoize the svg?

If that svg is truly the cause of your slow performance then by all means memoize it. But, if a simple icon is causing issues, why stop there? Why not use uncontrolled components with refs and event delegation to prevent re-renders of the input in general?

Yes, everyone should try to write performant code, but saying that you can achieve this by applying memoization without reason, in my opinion, is incorrect.

Don't get me wrong, you certainly make valid points. I only disagree on using memoization every time without a specific need.