Loading Routes Lazily

During the development time in react application when you run the application on the development server, it creates the bundle of your project. You can see that on the network section in the browsers developer tool, you find bundle.js with some memory and that memory depends on the size of the application. 

What it does is, bundled your application's component which you imported normally inside any component. It uses a large space. So there is an advanced concept we can use to reduce this and for that, the application should be configured with the webpack and react-router v4 to use this concept.

Sometimes it is needed to render a child component depending on some particular conditions. So in that case we have to download that component when it is required to render. It is an advanced concept and it is beneficial when we have large components to render. It can be achieved by code splitting and for that, we need webpack configured in the application.

So, let's work with the code part now.

First, we have to make HOC (Higher Order Component) which takes a component as an argument and sets the state in ComponentDidMount during the call of imported Component Asynchronously and renders accordingly.

import React, { Component } from 'react';

const AsyncComponent = (importComponent) => {
return class extends Component {
state = {
component: null
}

componentDidMount(){
importComponent()
.then((result) => {
this.setState({ component: result.default })
});
}

render(){
const C = this.state.component;
return C ? <C {...this.props} /> : null
}
}
}

export default AsyncComponent;

Make HOC according to the above code.

Secondly, we have to work on the component we want to render when needed. Normally we import components like

import SomeComponent from './SomeComponent';

But what it does is it downloaded that component initially because the keyword "import" behaves globally. So to restrict that we import component like

import AsyncComp from './AsyncComponent';

const AsyncComponent = AsyncComp(() => {
return import('./SomeComponent')
})

It imports HOC and imports a child component by taking as an argument and return the component when it is required. So it is downloaded at the time of render only.

Conclusion:

It is useful when you render any bigger chunks of components because it creates the extra bundle beside the main bundle when it is needed.

Comments

Popular posts from this blog

Comparing Application Sizes: ReactJS vs. SolidJS

Demystifying the "Mod_Security" Error: An In-Depth Analysis

Exploring onMount in SolidJS vs useEffect in ReactJS