As web applications grow in size and complexity, optimizing performance becomes critical. Every millisecond matters when it comes to providing a smooth user experience. This is where Memoization in React comes into play.
React provides two powerful techniques to optimize the rendering performance of React components:
- React memo for functional components
- React.PureComponent for class components
In this article, we’ll dive deep into how these two methods work and how you can use them to prevent unnecessary re-renders and speed up your React apps.
Understanding The Problem
Before we jump into the solutions, let’s first understand what problem we are trying to solve here.
React builds and maintains a virtual DOM to keep track of UI changes and render only what’s necessary. By default, it re-renders components whenever the parent component renders, regardless of whether the props or state changed.
This default behavior is great for simplicity but terrible for performance. Re-rendering everything on every update, even when nothing changed, leads to unnecessary work and slow UIs.
This is where memoization enters the picture.
What is Memoization in React?
Memoization is an optimization technique that caches the output of a function based on its inputs. For React components, memoization means that the component will not re-render if the props remain unchanged.
This tuning of the rendering behavior can lead to huge performance improvements by avoiding unnecessary re-renders.
Now let’s see how React provides memoization capabilities out of the box with React memo and React PureComponent.
Meet React memo()
React memo is a higher order component that memoizes functional components in React. Here is how you use it:
import React from 'react'; const MyComponent = (props) => { //... } export default React.memo(MyComponent);
By wrapping a functional component with React.memo, React will skip re-rendering that component if the props haven’t changed.
This can improve performance drastically in cases where functional components receive a lot of unnecessary updates.
Use Cases for React.memo()
Here are some common use cases where using React.memo really shines:
- Expensive computations inside functional components
If you have complex calculations, data manipulation, or sorting logic inside your functional components, it makes sense to memoize them. So the expensive work is skipped on subsequent renders unless the inputs change.
- Components that receive too many props
Sometimes components get overburdened with too many props for future proofing. Wrapping them with React memo means the component will only re-render if any of those relevant props change.
- Lists and other collection components
Rendering long lists can get slow due to the number of elements. Memoization ensures each item component only rerenders if IT’S data changes.
- General performance boost
In most cases, adding React memo improves performance by preventing avoidable re-renders. It’s a good default optimization.
Conditionally Applying Memoization with areEqual
The React memo method also allows providing a custom comparison function as the second argument. This compares previous and current props to decide whether to re-render or not.
const MyComponent = React.memo(MyExpensiveComponent, areEqual); function areEqual(prevProps, nextProps) { /* return true if passing nextProps to render would return the same result as passing prevProps to render, otherwise return false */ }
So you can customize the memoization logic, instead of just a shallow prop comparison. This way React.memo gives fine-grained control over when memoization should apply.
Class Component Memoization with React.PureComponent
React also provides memoization capabilities for class components with React.PureComponent. Components extending PureComponent implement a shallow comparison of props and state in the shouldComponentUpdate lifecycle method.
Here is an example of how to convert a normal React component class to a performant PureComponent:
import React from 'react'; class MyComponent extends React.Component { //... } // Convert to a PureComponent class MyComponent extends React.PureComponent { //... }
By extending PureComponent instead of Component, React will now shallowly compare state and props before deciding to re-render the component. If the props and state are equal, the component is not re-rendered.
This seems similar to functionality provided by React memo. So when should you use one vs the other?
React.memo vs React.PureComponent
Here is a quick comparison to help decide when to use which:
- React.memo is for function components. React.PureComponent is for class components.
- React.memo does a prop comparison. React.PureComponent shallowly compares state as well.
- React.memo accepts an optional comparison function. React.PureComponent just uses a shallow comparison.
So in essence, both provide memoization capabilities. Use React memo for function components and React.PureComponent for class component optimizations.
Why Memoization Matters
Let’s recap some key benefits of leveraging memoization in React apps:
- Avoid Unnecessary Re-renders
Memoization techniques like React.memo and PureComponent prevent re-rendering when the relevant props/state stays the same. This avoids unnecessary work.
- Optimized Performance
Skipping re-renders directly improves UI performance, responsiveness, and smoothness. Users perceive your app as quicker.
- CPU and Memory Savings
With fewer re-renders, React has less work to do. This lightens the load on CPU and memory.
As web apps grow, memoization helps control the rendering behavior and optimizations for perceivable speedups. The cost is relatively low given React provides these APIs out of the box.
So next time your React app feels slow, give React memo and React.PureComponent a try. Memorization is a proven optimization strategy.
Build Blazing Fast React Apps
While memoization sets the foundation, fully optimizing React application performance requires going deeper.
If you are looking for someone with expertise in building high-performance React apps, look no further.
Get in touch with me for consultation on your React project. My decade of experience with React and other front end technologies can take your web app’s speed and capability to the next level.
Related Articles
March 6, 2024
Setup WhatsApp Business API with Meta: A Step-by-Step Guide
Learn how to seamlessly integrate WhatsApp Business API with Meta, unlocking…
February 29, 2024
Power of React Lazy Loading for React Performance
React lazy loading defers the loading of non-essential components and assets…
February 28, 2024
Unleashing the Power of React Code Splitting
React code splitting improves page load times by splitting code into separate…