التخطي إلى المحتوى الرئيسي

React Code Splitting, How to improve performance of React application


In this article, I am trying to cover the following topics

1)  React Code Splitting

2)  React Lazy Loading

3)  Suspense in React

4) Error Boundary in React

The React app bundled their files using tools like Webpack or Browserfy. Bundling is a process that takes multiple files and merges them into a single file, which is called a bundle. The bundle is responsible for loading an entire app at once on the webpage. We can understand it from the below example.

App.js

import { add } from './add.js';  

console.log(add(16, 26)); // 42  

add.js

export function add(a, b) {  

  return a + b;  

}  

Bundle file as like below:

function add(a, b) {  

  return a + b;  

}  

console.log(add(16, 26)); // 42  

As our app grows, our bundle will grow too, especially when we are using large third-party libraries. If the bundle size gets large, it takes a long time to load on a webpage. For avoiding the large bundling, it?s good to start? splitting? your bundle.

React 16.6.0, released in October 2018, and introduced a way of performing code splitting. Code-Splitting is a feature supported by Webpack and Browserify, which can create multiple bundles that can be dynamically loaded at runtime.

Code splitting uses React. lazy and Suspense tool/library, which helps you to load a dependency lazily and only load it when needed by the user.

Advantage of  code splitting:

The performance of the app

The impact on memory

The downloaded Kilobytes (or Megabytes) size

React.lazy

The best way for code splitting into the app is through the dynamic import() syntax. The React.lazy function allows us to render a dynamic import as a regular component.

Before

import ExampleComponent from './ExampleComponent';  

  function MyComponent() {  

  return (  

    <div>  

      <ExampleComponent />  

    </div>  

  );  

}  

After

const ExampleComponent = React.lazy(() => import('./ExampleComponent'));  

  function MyComponent() {  

  return (  

    <div>  

      <ExampleComponent />  

      <AbcComponent />

      <HelloComponent />

    </div>  

  );  

}  

The above code snippet automatically loads the bundle which contains the ExampleComponent when the ExampleComponent gets rendered.

What is Suspense in React

If the module which contains the ExampleComponent is not yet loaded by the function component(MyComponent), then we need to show some fallback content while we are waiting for it to load. We can do this using the suspense component. In other words, the suspense component is responsible for handling the output when the lazy component is fetched and rendered.

import {Suspense,React,lazy} from 'react';

const ListExample2 = lazy(() => import('./ListExample2'));  
function Hello()
{
   return(<div>
    <Suspense fallback={<div>Loading...</div>}>
    <ListExample2 />
    </Suspense>
    </div>
    )
}

export default Hello;

The fallback prop accepts the React elements which you want to render while waiting for the component to load. We can combine multiple lazy components with a single Suspense component. It can be seen in the below example.

const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));  

const ExamComponent = React.lazy(() => import('./ ExamComponent'));  

  function MyComponent() {  

  return (  

    <div>  

      <Suspense fallback={<div>Loading...</div>}>  

        <section>  

          <ExampleComponent />  

          <ExamComponent />  

        </section>  

      </Suspense>  

    </div>  

  );  

}  

Note: React. lazy and Suspense components are not yet available for server-side rendering. For code-splitting in a server-rendered app, it is recommended to use Loadable Components.

What Error boundaries in React JS

If any module fails to load, for example, due to network failure, we will get an error. We can handle these errors with Error Boundaries. Once we have created the Error Boundary, we can use it anywhere above our lazy components to display an error state.

import MyErrorBoundary from './MyErrorBoundary';  

const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));  

const ExamComponent = React.lazy(() => import('./ ExamComponent'));  

  const MyComponent = () => (  

  <div>  

    <MyErrorBoundary>  

      <Suspense fallback={<div>Loading...</div>}>  

        <section>  

          <ExampleComponent />  

          <ExamComponent />  

        </section>  

      </Suspense>  

    </MyErrorBoundary>  

  </div>  

);  

Code of MyErrorBoundary.js

import React from "react";

export class MyErrorBoundary extends React.Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }
 
    static getDerivedStateFromError(error) {
      // Update state so the next render will show the fallback UI.
      return { hasError: true };
    }
 
    componentDidCatch(error, errorInfo) {
        console.log(error,errorInfo)
      // You can also log the error to an error reporting service
     // logErrorToMyService(error, errorInfo);
    }
 
    render() {
      if (this.state.hasError) {
        // You can render any custom fallback UI
        return <h1>Something went wrong.</h1>;
      }
 
      return this.props.children;
    }
  }

Example of Code Splitting using lazy ad Suspense?

Code of Exception handing under Event handler method:-

React provide try and catch block to handle error, try to write the code and catch block to define the error message.

Example

import React from "react";
export class ExceptionExample extends React.Component {
    constructor(props) {
      super(props);
      this.state = { error: null,a:"10",b:null,c:0 };
      this.handleClick = this.handleClick.bind(this);
    }
 
    handleClick() {
       
      try {
        var res = this.state.a / this.state.b
        this.setState({c:res})

        throw "error"
      //  alert("hello"+res);
        // Do something that could throw
     //   this.setState()
      } catch (error) {
        this.setState({ error });
      }
    }
 
    render() {
      if (this.state.error) {
        return <h1>Caught an error.</h1>
      }
     
      return (<div>
        <button onClick={this.handleClick}>Click Me</button>
        <br/>
        {this.state.c}
      </div>);
    }
  }


1)  create function component:-

import React from 'react';   
 
function NameList() {  
   
  return (  
    <div>  
        <h2>Rendering Lists inside component</h2>  
              
    </div>  
  );  
}  

export default  NameList;


2)  Create App.js top define suspense ad lazy


import React,{ lazySuspense }  from 'react'
//import NameList from './NameList'
const NameList = React.lazy(() => import('./NameList'));  
  
class App extends React.Component {  
  render() {  
    return (  
      <div>  
         <Suspense fallback={<div>Loading...</div>}> 
          <NameList></NameList>
          </Suspense>  
       
      </div>  
    )  
  }  

export default App;

3)  Code of Index.js file

  import React from 'react';
  import ReactDOM from 'react-dom';
  import './index.css';
  
  import reportWebVitals from './reportWebVitals';
  import App from './App'
  
  ReactDOM.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
    document.getElementById('root')
  );

  // If you want to start measuring performance in your app, pass a function
  // to log results (for example: reportWebVitals(console.log))
  // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
  reportWebVitals();


تعليقات

المشاركات الشائعة من هذه المدونة

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...