React lazy loading means that it will not be preloaded, but will be loaded only when a certain piece of code, a certain component or a certain picture is used; the reason why lazy loading is needed is because there are too many loads at the same time on the first screen The content will cause problems such as lag, slow response, and long user waiting time. For this, the lazy loading mechanism can be used to optimize.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
What is react lazy loading?
React lazy loading
1. What is lazy loading? Why do you need lazy loading?
Lazy loading: Will not preload, but only load them when a certain piece of code, a certain component or a certain picture needs to be used (delayed loading)
Reason: There are many pages and the content is Rich, long pages, and many pictures. Loading too much content on the first screen at the same time will lead to problems such as lag, slow response, and long user waiting time. We often use the lazy loading mechanism to optimize this.
2. Use lazy loading
Use React.lazy loading
//OtherComponent.js 文件内容 import React from 'react' const OtherComponent = ()=>{ return ( <div> 我已加载 </div> ) } export default OtherComponent // App.js 文件内容 import React from 'react'; import './App.css'; //使用React.lazy导入OtherComponent组件 const OtherComponent = React.lazy(() => import('./OtherComponent')); function App() { return ( <div className="App"> <OtherComponent/> </div> ); } export default App;
But this page will report an error. This error message reminds us that after React uses lazy, there will be a loading gap. React does not know what content to display during this gap, so we need to specify it. Next we need to use the Suspense loading indicator.
import React, { Suspense, Component } from 'react'; import './App.css'; //使用React.lazy导入OtherComponent组件 const OtherComponent = React.lazy(() => import('./OtherComponent')); export default class App extends Component { state = { visible: false } render() { return ( <div className="App"> <button onClick={() => { this.setState({ visible: true }) }}> </button> 加载OtherComponent组件 <Suspense fallback={<div>Loading...</div>}> { this.state.visible ? <OtherComponent /> : null } </Suspense> </div> ) } }
Recommended learning: "react video tutorial"
The above is the detailed content of What is react lazy loading. For more information, please follow other related articles on the PHP Chinese website!