Lazy loading in React.js is an effective way to enhance your app's performance by loading components only when they are needed. Rather than requiring users to wait while the entire application loads upfront—regardless of what they actually need—lazy loading allows you to divide your code into smaller, more manageable chunks. These chunks are then loaded on demand as users navigate through your app.
This approach significantly reduces the initial load time, ensuring that your app starts up faster and only the necessary data is downloaded. Users interact with your app more smoothly, as they're not burdened with loading content they aren’t immediately accessing.
By implementing lazy loading, you not only improve your app's speed but also optimize resource usage, delivering a more responsive and efficient user experience. It’s a smart strategy that aligns with modern best practices in web development.
There are several types of lazy loading we will discuss in this blog.
1. Dynamic Lazy Loading
importReact,{ lazy,Suspense}from"react";importHeaderfrom"@/app/components/common/header/Header";//dynamically importing the Post componentconstPost=lazy(()=>import("../../components/util-components/Post"));constDynamicLazyLoad=()=>{return(<div>{/* Using Suspense to render fallback while Post is dynamically loading */}<Header color="red">DynamicLazyLoad</Header><Suspense fallback={<div>Loading...</div>}><Post/></Suspense></div>);};exportdefaultDynamicLazyLoad;
Post Header
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vehicula, urna eu efficitur dapibus, tortor sapien ultricies arcu, nec elementum magna ligula sit amet odio. Praesent luctus, erat eu aliquet vulputate, erat nisi scelerisque ligula, sit amet euismod elit nulla eget neque. Curabitur scelerisque felis nec ante condimentum, ac lobortis lorem viverra. Sed vel sagittis purus. Cras in ex arcu. Duis sagittis, felis vel vehicula bibendum, libero lectus pellentesque elit, in dapibus metus nisl a elit. Integer et ex id arcu vehicula lacinia. Integer consectetur ipsum non purus eleifend, at cursus justo sagittis. Nam fermentum magna sit amet urna ultricies, nec
Post Footer
2. Lazy Load On Interaction
importReact,{ useState }from"react";importHeaderfrom"@/app/components/common/header/Header";constLazyLoadOnInteraction=()=>{const[Post, setPost]=useState(null);consthandleClick=()=>{import("../../util-components/Post").then((module)=>{setPost(()=> module.default);});};return(<div><Header color="red">LazyLoading on Interaction</Header>{Post?<Post/>:<button onClick={handleClick}>LoadPost</button>}</div>);};exportdefaultLazyLoadOnInteraction;
Lazy Loading on Interaction
3. Lazy Loading with Intersection Observer
importReact,{ useState, useRef, lazy,Suspense}from"react";importuseIntersectionObserverfrom"../../hooks/useIntersectionObserver";importHeaderfrom"@/app/components/common/header/Header";constPost=lazy(()=>import("../../components/util-components/Post"));constLazyIntersectionObserver=()=>{const[shouldRenderPost, setShouldRenderPost]=useState(false);const postRef =useRef(null);consthandleIntersect=([entry])=>{if(entry.isIntersecting){setTimeout(()=>{setShouldRenderPost(true);},1000);//setTimeout is only for loading effect - dont use in production}};useIntersectionObserver(postRef, handleIntersect,{treshhold:0});return(<div><Header color="red">LazyLoadingwith the IntersectionObserver</Header><div style={{height:"500px"}}>SomeContent before the post</div><div ref={postRef}>{shouldRenderPost ?(<Suspense fallback={<div>LoadingSuspense...</div>}><Post/></Suspense>):(<div>Loading...</div>)}</div><div style={{height:"500px"}}>SomeContent after the post</div></div>);};exportdefaultLazyIntersectionObserver;
When using React Router, you can lazy load components associated with specific routes. This ensures that only the components necessary for the current route are loaded, reducing the initial bundle size.
Native HTML Loading Attribute: The simplest method for lazy loading images is to use the loading="lazy" attribute on the '<img>' tag. This instructs the browser to delay loading the image until it’s in or near the viewport.