Skip to main content

PureComponent and React.memo in React (Live Playground)

Optimizing the performance of your React application is essential for providing a smooth user experience. In this tutorial, we'll discuss PureComponent and React.memo, two tools that help prevent unnecessary component re-renders.

PureComponent

PureComponent is a base class for class components that automatically implements a shallow comparison for shouldComponentUpdate. It prevents unnecessary re-renders when the component's state or props have not changed.

Using PureComponent

JavaScript
import React, { PureComponent } from 'react';

class MyComponent extends PureComponent {
constructor(props) {
super(props);
this.state = { counter: 0 };
}

incrementCounter = () => {
this.setState(prevState => ({ counter: prevState.counter + 1 }));
};

render() {
console.log('MyComponent re-rendered');
return (
<div>
<button onClick={this.incrementCounter}>Increment</button>
<p>Counter: {this.state.counter}</p>
</div>
);
}
}

export default MyComponent;
Live Playground, Try it Yourself

React.memo

React.memo is a higher-order component that does a shallow comparison of a functional component's props, preventing re-renders when the props have not changed.

Using React.memo

JavaScript
import React, { useState } from 'react';

const MyComponent = React.memo(function MyComponent({ value, onClick }) {
console.log('MyComponent re-rendered');
return (
<div>
<button onClick={onClick}>Increment</button>
<p>Counter: {value}</p>
</div>
);
});

function App() {
const [counter, setCounter] = useState(0);

const incrementCounter = () => {
setCounter(prevCounter => prevCounter + 1);
};

return (
<div>
<MyComponent value={counter} onClick={incrementCounter} />
</div>
);
}

export default App;
Live Playground, Try it Yourself

Conclusion

PureComponent and React.memo are valuable tools for optimizing React applications by preventing unnecessary component re-renders. Use PureComponent for class components and React.memo for functional components when shallow comparisons of state or props are sufficient for determining whether a component should update. These optimizations can greatly improve the performance and user experience of your application.