Difference between pureComponent and component in React


This is an short tutorials explains about difference between PureComponent and Component.

Normal Component example

Normal components are created in every application by extending React.component for Class components.

  • Created a component using class keyword
  • Extends React.component
  • It has callback lifecycle methods like componentWillMount etc.
  • Also can add event handler methods, For example, Adding button and its event handler click event
  • The state can be Scalar types like Integer,String and nested data structures.
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class NormalComponent extends Component {
    constructor(props) {
        super(props);

    }

    componentWillMount() {

    }

    componentDidMount() {

    }

    componentWillReceiveProps(nextProps) {

    }

    shouldComponentUpdate(nextProps, nextState) {

    }

    componentWillUpdate(nextProps, nextState) {

    }

    componentDidUpdate(prevProps, prevState) {

    }

    componentWillUnmount() {

    }

    render() {
        return (
            <div>

            </div>
        );
    }
}

NormalComponent.propTypes = {

};

export default NormalComponent;

React PureComponent example

PureComponent are created by extending React.PureComponent with class keyword

  • Created components with class keyword
  • Extends React.PureComponent
  • No callback or life cycle methods
  • State can be scalar types only
import React, { PureComponent } from 'react'
export default Class PureComponentExample  extends React.PureComponent{
       render() {
        return (
            <div>

            </div>
        );
    }
}

Difference between pureComponent and normal Component in react

Normal React component does not call shouldComponentUpdate by default.

Pure components calls shouldComponentUpdate and check shallow comparision logic to render a component or not, that means PureComponent is used when there are much changes in state or props

If you parent component is pure component, and all children components are compulsory to be pure components.

Conclusion, When there are heavy state/prop changes in components, use Normal Component.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.