Welcome to the latest addition to our React JS tutorial series! Today, we're diving deep into the fascinating world of Pure Components. 💡
In React, a PureComponent is a built-in class that helps optimize rendering by memorizing the component based on its props and state. This can significantly boost performance in our applications.
React updates components when their props or state change. However, sometimes components re-render even when these values don't change. Pure Components come to the rescue by checking if the component needs to be re-rendered based on the changes in props and state. If they're the same, React skips the re-render, saving precious resources.
Let's create a simple Pure Component:
import React from 'react';
class Counter extends React.PureComponent {
render() {
return <h1>Count: {this.props.count}</h1>;
}
}
export default Counter;In the above code, we extended the built-in React.PureComponent class to create a Pure Component. ✅
Under the hood, PureComponents use a method called shouldComponentUpdate to determine if a re-render is necessary. In our PureComponent, React compares the current props and state with the next ones and re-renders only if they differ.
Let's create a simple CounterApp using PureComponents:
import React from 'react';
import Counter from './Counter';
class CounterApp extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return <Counter count={this.state.count} onIncrement={this.incrementCount} />;
}
}
export default CounterApp;
// Counter.js
import React from 'react';
class Counter extends React.PureComponent {
render() {
return <h1>Count: {this.props.count}</h1>;
}
}
export default Counter;In this example, we have a CounterApp that maintains a count and a Counter component that displays it. When the "incrementCount" method is called, the count state is updated, causing the CounterApp to re-render. Since Counter is a PureComponent, it checks if the count prop has changed. If it hasn't, it skips the re-render, saving valuable resources. ✅
What is a PureComponent in React?
Stay tuned for the next part of our React JS tutorial series, where we'll explore Functional Components! 🎯 Happy coding! 🚀