Wednesday, May 6, 2020

React.memo example

React.memo was introduced in React 16.6 to create performance efficient function components, these components are similar to PureComponents except that they are function based. These components will re-render only when the props of the component changes and not when the parent component re-renders, thereby reducing the number of render cycles and improves the component performance.

In the below example we will create a React.memo component MyMemoComponent which will take a prop msg from the parent and display it. Remember that the memo component will only re-render when the props passed to it changes.
import React from 'react';

class App extends React.Component {
  state = {
    myState: false
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <MyMemoComponent msg="Hello from Parent"/>
        </header>
      </div>
    );
  };
}

const MyMemoComponent = React.memo(function MyMemoComponent(props) {
  return (
    <div>
      <p>Memo Component</p>
      <p>Props message: {props.msg}</p>
    </div>
  )
});

export default App;

The output will be as follows.




Search Flipkart Products:
Flipkart.com

No comments: