I know that using React.memo()
to memoize components / parts of components is generally a good practice, but I find myself memoizing every single field on forms implemented using React Hook Form. Since RHF uses uncontrolled components, it does not seem to be a problem: the components seem to update just fine, and I do see a performance improvement.
Still, my instinct tells me that memoizing almost everything is a bad practice. Is it a bad practice? Is there some other way that I should economize on renders?
Your instinct is correct. If React.memo()
everything makes React more efficient, it should be a default behavior, not only an optional (like pure function).
For shorter explanation:
React.memo()
prevents some redundant rerender by comparing the component's previous and current props.
<Parent>
<Child />
</Parent>
Normally, when the parent rerenders, the child rerenders as well by default.
If the props passed into Child
are not changed when Parent
rerender, Child
does not rerender if you use React.memo()
on Child
The question here is: why React knows props on Child
was not changed in the current rendering phase?
The answer is: React itself has to do a comparison, and it is the cost of React.memo()
If the time to comparison > the time to just rerender the whole Child
component, it even slows down your rerendering time.
You only need to use React.memo()
for some huge things (Table with a lot of rows and for some reasons it does not have pagination).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With