An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
How to implement Lazy Loading in REACT | code splitting
Here is a simple App component:
import Bids from './components/Pages/OnlineAuction/Auctions/Bids'import { GeneralGoods } from './components/Pages/Galleries/GeneralGoods/GeneralGoods'class App extends Component { render() { return ( <div> <BrowserRouter> <div> <Routes> <Route path="/galleries-general-goods" element={<GeneralGoods />} /> </Routes> </div> </BrowserRouter> </div> ); }}export default App;
React imports all the components as soon as the Application starts. But there's a problem to this.
React takes some time to load all components and the App is accessible only after all the components have been imported.
So if a user to your site or app does not visit 7 out of 8 of your components, they will still be loaded and this has an impact on the performance of your app.
Luckily, there is a solution made available to us by REACT.
Lazy Loading
We can choose when to load the required components. So components are only imported by REACT App only when the relevant route is visited.
Below are the 5 simple steps to achieve this:
1- Import Lazy & Suspense from REACT.
import {lazy, Suspense} from 'react'
2- Use the import function
const myComponent = () => import('./components/myComponent')
3- Wrap your imports in lazy()
const myComponent = lazy (() => import('./components/myComponent'))
4- Wrap the returns inside Suspense()
function App() { return ( <Suspense> //ALL YOUR RETURN COMPONENTS HERE </Suspense>)}
5- Specify fallback for Suspense()
<Suspense fallback={<div><p>I am Loading</p></div>} //ALL YOUR RETURN COMPONENTS HERE</Suspense>
Complete component should be something like this:
import {lazy, Suspense} from 'react'import {Switch, Route} from 'react-router-dom'const Bids = lazy(() => import('./components/Bids'))const GeneralGoods = lazy(() => import('./components/GeneralGoods'))function App() { return ( <Suspense fallback={<div><p>I am Loading</p></div>} ><Switch> <Route path="/bids" exact> <Bids /> </Route> <Route path="/goods" exact> <GeneralGoods /> </Route></Switch> </Suspense> )}
If you managed to reach this far, thank you very much. I also post similar content on LinkedIn at [https://www.linkedin.com/in/eng-sedrick-nyanyiwa-39110aa6]
Original Link: https://dev.to/nyanyiwast/how-to-implement-lazy-loading-in-react-code-splitting-1je6
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To