20 Feb 2024




Intermediate

In React.js, a pure component is a specific type of component that enhances performance by reducing unnecessary re-renders. Pure components are typically created by extending React's PureComponent class or by using the React.memo() higher-order component.

The key characteristic of a pure component is that it implements a shouldComponentUpdate() method that performs a shallow comparison of the component's props and state. If the shallow comparison determines that the new props or state are different from the previous ones, the component will re-render; otherwise, it will not re-render.

By avoiding re-renders when the props and state haven't changed, pure components help optimize performance, especially in large and complex React applications where re-rendering can be expensive in terms of processing power and rendering time.

It's important to note that pure components work best when the props passed to them are immutable or are not being mutated in a way that affects the shallow comparison. If the props are mutable and their reference remains the same even when their values change, the shallow comparison may not detect the changes correctly, leading to unexpected behavior.

In summary, pure components in React.js are components optimized for performance by reducing unnecessary re-renders through shallow comparisons of props and state.

Example:

Examples of how you can define a pure component using both React.PureComponent and React.memo():

  • Using React.PureComponent:
import React from 'react';

class MyPureComponent extends React.PureComponent {
  render() {
    return <div>{this.props.value}</div>;
  }
}

export default MyPureComponent;

In this example, MyPureComponent extends React.PureComponent. React's PureComponent class automatically implements the shouldComponentUpdate() method with a shallow comparison of props and state.

  • Using React.memo():
import React from 'react';

const MyFunctionalComponent = React.memo(({ value }) => {
  return <div>{value}</div>;
});

export default MyFunctionalComponent;

In this example, MyFunctionalComponent is a functional component wrapped with React.memo(). This higher-order component memoizes the component to prevent re-renders if the props haven't changed since the last render.

Both examples achieve the same goal of optimizing performance by preventing unnecessary re-renders when the component's props or state haven't changed.

reactjs
pure-component