React.memo is not memoization

Posted on  by Leonardo Lemos

react

In a recent conversation with some colleagues at work, I suggested using React.memo for a component we were building. However, one of my colleagues questioned whether this higher-order component (HOC) would provide any optimization benefits. It seems that many software engineers don't fully understand the memoization that React offers, so I wanted to clarify it in this post.

Memoization is the process of optimizing performance by caching the result of a computation and associating it with the parameter used to calculate it. However, React's version of memoization is different. When a component is wrapped in React.memo, React's reconciliation algorithm only compares the previous and current properties to determine whether to re-render the component. It doesn't cache all the properties passed to it or keep a history of properties to return instant results based on previous function calls. Instead, it only skips re-rendering a component if the props remain unchanged.

While memoization can help optimize performance in some cases, it's not a one-size-fits-all solution. The React documentation cautions that memoization does not guarantee optimization, and I agree. Memoizing everything can lead to slower reconciliation due to an overload of comparisons. Therefore, React.memo is most useful for pure function components or components that frequently re-render with the same props and output. (Image below)

[React memo is not memoization] Diagram parallel comparison

In conclusion, technology is a trade-off, and there is no silver bullet for all problems. If you need to pass a function or complex data, other optimizations may be necessary.

Credits & References

Like this post? Share it with your friends! 😃
Want to read it later? I recommend Instapaper!