sudotunji
sudotunji

Reputation: 11

How to avoid initial lag after input using Material UI

Context
I have a carousel of MUI cards for a website that I'm building that is a box using a stack as it's underlying component. A problem that's come up is that whenever I try to scroll, there's at least a 4 second lag before seeing any new render. I tried

  1. cropping down the images
  2. compressing them
  3. converting to .webp's
  4. moving the logic into one place instead of passing props

Thouhgts

Cut off a lot of the unnecessary bits

Index.tsx snippet mapping through data

<Box
  component={Stack}
  direction="row"
  spacing={5}
>
{carouselData.map((item: CarouselProps) => (
  <CreativeCarousel
    src={item.src}
  />
))}
</Box>

Carousel Component

//Consistent typing for properties
export type CarouselProps = {
  src: StaticImageData;
};

const CreativeCarousel = (props: CarouselProps) => {
  return (
    <Card sx={{ maxWidth: 300, minWidth: 300, height: "100%" }}>
      <CardMedia component="img" height="75" image={props.src.src} />
    </Card>
  );
};
export default CreativeCarousel;

Upvotes: 0

Views: 662

Answers (1)

sudotunji
sudotunji

Reputation: 11

Troubleshooting
The lag went away after removing the <CardMedia /> so my guess is that rerendering full-res images for every frame of scrolling isn't the most optimal move.

Solution

But replacing the underlying component from the standard html img to an optimized Next.js Image most definitely was. I was under the impression that I needed to pass a component as a property or else I'd need to use an img like what was used in the example. I only found out later that I could also pass react nodes as children in the API page.

const Carousel = () => {
  return carouselData.map((item) => (
    <Card
      key={item.heading}
      sx={{ maxWidth: 300, minWidth: 300, height: "100%", mx: 4 }}
    >
      <CardMedia sx={{ width: "100%", height: "auto" }}>
        <Image
          alt={item.heading}
          src={item.src}
          layout="responsive"
        />
      </CardMedia>
    </Card>
  ));
};
export default Carousel;

Upvotes: 1

Related Questions