@orpha
To implement lazy loading in React.js, you can make use of React's lazy
function along with the Suspense
component.
Here are the steps to follow:
1
|
import React, { lazy, Suspense } from 'react'; |
1 2 3 4 5 6 7 |
import React from 'react'; const LazyComponent = () => { return <div>This is the lazy loaded component!</div>; }; export default LazyComponent; |
1 2 |
import React, { lazy, Suspense } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); |
1 2 3 4 5 6 7 8 9 10 |
const App = () => { return ( <div> <h1>Lazy Loading Example</h1> <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> </div> ); }; |
Lazy loading allows you to improve initial page load time by splitting your code into smaller chunks, and only loading them when needed.