react

React pure component – explained


In JavaScript, a pure function will always return the same result in other words Its return value is the same for the same arguments.

In React the memo function is used to create React pure components. A pure component in React is a component that always renders the same output, given the same arguments.

Let’s Understand with code example, we will create a component called Car

const Car = ({ brand }) => {
  console.log(`rendering ${brand}`);
  return <p>{brand}</p>;
};

In the code snippet above Car is a pure component. The output is always a paragraph that displays the brand property. If the brand provided as a property is the same, the output will be the same:

Let’s Simplify above statement, consider the code snippet below:

function App() {
    const [cars, setCars] = useState(["BMW", "Audi", "Tata"]);
    return (
      <>
        {cars.map((brand, i) => (
          <car key={i} brand={brand} />
        ))}
        <button onClick={() => setCars([...cars, prompt("car brand")])}>
          Add a car
        </button>
      </>
    );
  }

The code snippet above uses the Car component. After the initial render, the console reads:

rendering BMW
rendering Audi
rendering Tata

When the “Add a Car” button is clicked, the user is prompted to add a car. If we add a car brand “Kia,” we see that all Car components are re-rendered:

rendering BMW
rendering Audi
rendering Tata
rendering Kia

Also, In the code snippet above every time, we are adding a new car brand every car component is being rendered.

as I mentioned earlier in the article, a pure component in React is a component that always renders the same output, given the same arguments. so in this case Car component is a pure component & there shouldn’t be a render for each of these if the properties haven’t changed.

To solve this issue we use memo function.

import React, { useState, memo } from "react";

const Car = ({ brand }) => {
  console.log(`rendering ${brand}`);
  return <p>{brand}</p>;
};

const PureCar = memo(Car);

Here, we’ve created a new component called PureCar. PureCar will only allow the Car to render when the properties change. now we will replace car component with PureCar component like below:

Cars.map((brand, i) => <PureCar key={i} brand={brand} />);

Now if every time we add a new car brand we will only see one render.

React pure component Example

A simple React class component looks like below:

class Car extends React.Component {
    render() {
      return (
        {brand} is a good Car!
      )
    }
  }

A Pure React class component looks like below:

class Car extends React.PureComponent {
    render() {
      return (
        {brand} is a good Car!
      )
    }
  }

In conclusion React Pure Component is the same as React.memo, but React Pure Component is only for class components & React.memo is only for function components.


Share on social media

//