DEV Community

Herat Dhruv
Herat Dhruv

Posted on • Edited on

is it necessary to use lazy 😴 and suspense 🕵 everywhere in the repo? 👨‍💻 this could cause CLS 📊 issue in web performance.

Recently i am working on web performance optimisation in my new organization. where i found one of the classic case which was causing a performance issue and impacting CLS webvital metric.

Due to which i am excited to share this with you guys. So everyone should get benefited using this way of approaching a problem.

One of the classic example when react suspense will no use.

Parent component

  • fetching data for child component lets say carousel
  • passing carousel list to carousel component

Child component [Carousel component]

  • display placeholder
  • display list of carousel
  • in case of no data it should not display placeholder as well as list of carousel and return null
// Pseudocode
import { lazy } from "react";
const CarouselComponent = lazy(() => import("../pages/CarouselComponent"));

function ParentComponent(){

const {carouselData} = getCarousel();// carousel data fetching hook

return (
   <Suspense fallback={<CarouselPlaceholder />}>
    <CarouselComponent carouselData={carouselData}>
   </Suspense>
)};

function CarouselComponent({carouselData}){
// undefined can be received from API
if(!carouselData) return null; 

return (
  {carouselData.length > 0? <CarouselList /> : <CarouselPlaceholder />})
}

Enter fullscreen mode Exit fullscreen mode

What could be wrong in the above code?

  • Fallback will not work CarouselComponent is wrapped with Suspense but CarouselComponent does not have any promises inside it due to which fallback ie. <CarouselPlaceholder /> will never work.

by the time carouselData is undefined or null the component will not render anything. and once the data is available it will render component with data. This will sudden shift in layout.

This problem will introduce a CLS issue in your web application.

  • for such a small file of CarouselComponent, which was not more than 2Kb gzip file it is necessary to use Lazy for code splitting? IMO we should not.

please fill free to share your experience for such a weird issues while dealing with web performance.

Top comments (0)