Using PureComponent and React.memo to improve Performance in React
Introduction
PureComponent in React is built on the concept of Pure Function. In this article, let's dive into PureComponent and the memo hook in React, as well as how to apply these tools to improve performance in React applications.
What is a Pure Function?
First off, it's important to understand the concept of a Pure Function, which will always return the same result with the same input parameters. To put it simply, the same input will always yield the same output.
For example:
What is a Pure Component?
In React, a PureComponent is considered a component that only renders when there's a change in props or state, where the change in props or state is determined based on shallow equality checking.
Here, I'll provide two ways to create a Pure Component in React.
1. Class Component
Although Class Components are no longer encouraged for use in React, newer versions of React still haven't completely removed Class Components, indicating that they haven't entirely replaced Functional Components. A typical Class Component extends from React.Component, but to initialize a Pure Component, you just need to replace it with React.PureComponent.
For example:
Here, MyComponent is defined as a PureComponent and will only render when there's a change in props or state. It's important to note that the comparison mechanism of PureComponent is shallow equality checking, so changing state or props can only involve assigning a new value.
For React components, there's a provided method called shouldComponentUpdate, which allows custom conditions for determining when a Class Component should render. Here's an example of how to use it:
2. Functional Component
To create a Pure Functional Component, we use React.memo. This function takes two parameters:
- The component you want to make a Pure Component.
- Optional: a propsAreEqual callback to customize rendering.
Here's an example:
Here, React.memo is considered a Higher Order Component (HOC) with an input of a Functional Component and returns a Pure Component.
Conclusion
In this article, I've introduced you to the concept and methods of initializing a PureComponent from both a Class Component and a Functional Component. Both approaches support custom functions that allow you to implement conditions to control the rendering of your application based on your project's needs. This is one of the simplest and most effective ways to improve performance for React applications.
Feel free to share your thoughts in the comments!
Comments
Post a Comment