React JS Tutorial: Pure Components 🎯

beginner
14 min

React JS Tutorial: Pure Components 🎯

Welcome to the latest addition to our React JS tutorial series! Today, we're diving deep into the fascinating world of Pure Components. 💡

Understanding 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.

Why Pure Components? 🤔

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.

Creating a Pure Component 🎨

Let's create a simple Pure Component:

jsx
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. ✅

Pure Component and shouldComponentUpdate 📝

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.

A Practical Example 🎯

Let's create a simple CounterApp using PureComponents:

jsx
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. ✅

Quiz Time! 📝

Quick Quiz
Question 1 of 1

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! 🚀