Wednesday, May 6, 2020

React.memo & React.lazy in React 16.6

React 16.6 introduces 2 main features React.memo and React.lazy

React.memo
is similar to PureComponent, it only re-renders if its props are changed. They both offer performance booster to the component by reducing the number of renders. The difference is that PureComponent works with classes and React.memo works with functions.
When a component is wrapped in React.memo, react renders the component and stores the rendered result like a cache. When the next render is due react checks if the props are the same, if so react re-uses the stored output instead of re-rendering the component, this helps improve the performance.

The syntax for React.memo component is as follows.

const MemoComponent = React.memo(function MemoComponentFunction(props) {
  return (
    <div>
      <!-- Memo component content -->
    </div>
  )
});

export default MemoComponent;

React.lazy
is a new function introduced in React 16.6 which helps in lazy loading React components through code-splitting. To understand this we should first go to the basics of how React applications are bundled and rendered to the browser.

In the React Environment setup post we saw how the React components are compiled and bundled before being rendered to the browser. We use Bable to compile the react Application and web-pack to bundle the compiled JavaScript into a bundle.js file.

If the Application grows bigger and uses many 3rd part components then the size of the bundle will grow thereby increasing the initial load time of the Application. To avoid this we can use code-splitting to create multiple bundle files and only the bundle file required to load the initial set of components will be loaded at first other component bundles will be loaded dynamically based on the need.

React.lazy is used to lazy load React components which might be in the same or different bundle file. The Suspense component supports the lazy loading by providing a fallback UI (Loading …) till the dependent component / bundle is loaded dynamically.

Following is the syntax to use React.lazy with Suspense to lazy load React components.

import React, {Suspense} from 'react';
const ChildComponent = React.lazy(() => import('<dependent component path>'));

class App extends React.Component {
  render() {
    return (
      <div>
        <Suspense fallback={<Fallback UI text>>
          <Dependent Component/>
        </Suspense>         
      </div>
    );
  };
}


Search Flipkart Products:
Flipkart.com

No comments: