Full Stack Development

Pure Components

by Tomas Trescak t.trescak@westernsydney.edu.au

Optimisations

Unpure components

      import React, { render } from 'react';

const NonPureComponent = ({ message }) => {
  console.log('rendered');
  return <div>{message}</div>;
};

const ParentComponent = () => {
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        Increment Count: {count}
      </button>
      <NonPureComponent message="Hello from Non-Pure Component!" />
    </div>
  );
};

render(<ParentComponent />);
    

Optimisations

Pure components

      import React, { render, memo } from 'react';

let PureComponent = ({ message }) => {
  console.log('rendered');
  return <div>{message}</div>;
};

PureComponent = memo(PureComponent)

const ParentComponent = () => {
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        Increment Count: {count}
      </button>
      <PureComponent 
        message="Hello from Pure Component!" 
      
      />
    </div>
  );
};

render(<ParentComponent />);