По работе была задача уменьшить размер React приложения чтобы быстрее загружалось ©
Начиная с версии 16.6 в Реакте есть встроеный «ленивый загрузчик» модулей: React.lazy. Работает он пока неполноценно (только для export default компонентов и нет ServerSide рендеринга), но зато в «одну строчку» и подхватывается биледрами типа WebPack.
А вот добавление loading/fallback компонента в «одну строчку» разработчики забыли, пришлось написать свой HOC (High Order Component) для помощи стандартному React.lazy()
Встречайте withSuspense() для lazy loading компонентов в React:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { CircularProgress, LinearProgress } from '@material-ui/core/'; | |
/** | |
* Wraps the React Component with React.Suspense and FallbackComponent while loading. | |
* @param {React.Component} WrappedComponent — lazy loading component to wrap. | |
* @param {React.Component} FallbackComponent — component to show while the WrappedComponent is loading. | |
*/ | |
export const withSuspense = (WrappedComponent, FallbackComponent = null) => { | |
return class extends React.Component { | |
render() { | |
if (!FallbackComponent) FallbackComponent = <LinearProgress />; // by default | |
return ( | |
<React.Suspense fallback={FallbackComponent}> | |
<WrappedComponent {…this.props} /> | |
</React.Suspense> | |
); | |
} | |
}; | |
}; | |
… | |
// Usage | |
const lazySomeComponent = React.lazy(() => import('./xxx/SomeComponent')); | |
export const SomeComponent = withSuspense(lazySomeComponent); | |
export const SomeComponentWithCircularProgress = withSuspense(lazySomeComponent, <CircularProgress />); | |
export const SomeComponentWithDiv = withSuspense(lazySomeComponent, <div>Loading…</div>); |
Пользуйтесь на здоровье 🙂