ReactJS – Component vs PureComponent


In this article, we are going to see the difference between Component and PureComponent. In ReactJS, Components are widely used to make an App more efficient and effective to use.

ReactJS provides two different ways to use components – Component or PureComponent.

Component

It is the type of component which re-renders itself every time when the props passed to it changes or its parent component re-renders.

Our first component in the following example is App. This component is the parent of the Comp1 component. We are creating Comp1 separately and just adding it inside the JSX tree in our App component. Only the App component needs to be exported.

Example

App.jsx

import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = { color: '#000' };
   }
   render() {
      return (
      <div>
         <h1 style={{ color: this.state.color }}>Tutorialspoint</h1>
         <button onClick={() => this.setState({ color: '#ff0000' })}>
            Change Color
         </button>
         <Comp1 />
      </div>
   );
   }
}

class Comp1 extends React.Component {
   render() {
      alert('Comp1 component is called');
      return (
         <div>
            <h1>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;

Output

The above code will generate the following result.

PureComponent

It is the type of component which re-renders only when the props passed to it changes and not even if its parent component re-renders or if the shouldComponentUpdate()method is called. It is greatly used to enhance the performance of a web application.

In the following example, we are going to use the PureComponent with Comp1 component so that it only re-renders if the props passed to it changes.

Example

App.jsx

import React from 'react';
class App extends React.Component {
   constructor() {
      super();
      this.state = { color: '#000' };
   }
   render() {
      return (
         <div>
            <h1 style={{ color: this.state.color }}>Tutorialspoint</h1>
            <button onClick={() => this.setState({ color: '#ff0000' })}>
               Change Color
            </button>
            <Comp1 />
         </div>
      );
   }
}

class Comp1 extends React.PureComponent {
   render() {
      alert('Comp1 component is called');
      return (
         <div>
            <h1>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;

Output

The above code will generate the following result.

Updated on: 18-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements