Lazy Loading
Lazy Loading:
1. Create an asyncComponent.js:
import React, { Component } from 'react';
const asyncComponent = (importComponent) => {
return class extends Component {
state = {
component: null
}
componentDidMount () {
importComponent()
.then(cmp => {
this.setState({component: cmp.default});
});
}
render () {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
}
export default asyncComponent;
2. In the main App.js where we have all the routing setup:
import asyncComponent from './hoc/asyncComponent/asyncComponent';
instead of
import MyComponent from '../path/to/MyComponent';
load the component asynchronously using the following code:
const asyncMyComponent = asyncComponent(() => {
return import('../path/to/MyComponent');
});
And in the routing use the async component:
<Switch>
<Route path="/mycomponentpath" component={asyncMyComponent} />
<Redirect to="/" />
</Switch>
Comments
Post a Comment