[React] Asynchronously Load webpack Bundles through Code-splitting and React Suspense
One approach to building high performance applications with webpack
is to take advantage of code-splitting to only load the needed JavaScript on initial load and asynchronously load additional JavaScript bundles when needed. In this lesson, we'll create add some code-splitting to our placeholder application and configure our project to support the dynamic import()
syntax.
Install:
npm i -D @babel/plugin-syntax-dynamic-import
Add plugin into webpack config:
plugins: [ ... '@babel/plugin-syntax-dynamic-import' ]
What we want to do is lazy loading a Warning component, and also utilize the code spliting from webpack:
Here is the component we want to lazy load in:
import React from 'react' export default () => <span className={'warning'}>Take it easy!</span>
App.js:
import React from 'react' import {hot} from 'react-hot-loader' const Warning = React.lazy(() => import('./Warning')) class App extends React.Component { state = { count: 0 } increment = () => { this.setState(state => ({count: state.count + 1})) } decrement = () => { this.setState(state => ({count: state.count - 1})) } render() { const {count} = this.state return ( <div> <h1>Hello World.</h1> <h2 className={count > 10 ? 'warning' : null}> Count: {count} </h2> <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> {count > 10 ? <React.Suspense fallback={null}> <Warning /> </React.Suspense> : null} </div> ) } } export default hot(module)(App)
We use React.lazy + dynamic import syntax:
const Warning = React.lazy(() => import('./Warning'))
Then we use lazy loaded Warning component with React.Suspense:
<React.Suspense fallback={null}> <Warning /> </React.Suspense>
'fallback' take a jsx element which will be shown when doing the lazy loading.
So what if the Warning component failed to load?
Here is where Error Boundries comes in to play:
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, info) { // You can also log the error to an error reporting service logErrorToMyService(error, info); } render() { if (this.state.hasError) { // You can render any custom fallback UI return <h1>Something went wrong.</h1>; } return this.props.children; } } export defualt MyErrorBoundry;
Then wrap your Suspense component with boundry:
<MyErrorBoundary> <React.Suspense fallback={null}> <Warning /> </React.Suspense> </MyErrorBoundary>
Now we can get benifits from lazy loading and also safety from the boundry
More about Code splitting.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-03-20 [Angular] Reactive Form -- FormControl & formControlName, FormGroup, formGroup & formGroupName
2016-03-20 [Angular 2] Using the @Inject decorator
2016-03-20 [WebStrom] Cannot detect file change to trigger webpack re-compile
2016-03-20 [TypeScript] Avoid any type
2016-03-20 [Angular 2] Injecting a Service
2016-03-20 [Angular 2] Event in deep
2015-03-20 [Javascript] Get Started with LeafletJS Mapping