All Lottie Animations run at once when a page gets open

Hi
I’m using @lottiefiles/react-lottie-player package for React, in my homepage I have about 14 unique Lottie Files, the problem is when someone opens the site in a browser, the browser forces your computer CPU and takes a lot of RAM. I have used Elementor, in Elementor you have Viewport option, which makes the animation only be played you it’s visible for the user. It’s been days I’m searching to find an option to do me the same thing in for React Package, But I haven’t got anything.
My question is, is there any way to make this possible? Or is there any different package that have this option?
Thanks.

Hello,

To optimize the performance of Lottie animations in your React application, you can use the Intersection Observer API in conjunction with the @lottiefiles/react-lottie-player package. This API allows you to control the play state of animations based on their visibility in the viewport, similar to the viewport feature in Elementor.

Here’s a simplified example of how you might implement this:

import React, { useEffect, useRef } from 'react';
import { LottiePlayer } from '@lottiefiles/react-lottie-player';

const LottieAnimation = ({ animationData }) => {
  const animationRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            animationRef.current.play();
          } else {
            animationRef.current.stop();
          }
        });
      },
      { threshold: 0.5 } // Trigger when 50% visible
    );

    const animationElement = animationRef.current;
    observer.observe(animationElement);

    return () => observer.unobserve(animationElement);
  }, []);

  return (
    <LottiePlayer
      ref={animationRef}
      animationData={animationData}
      style={{ width: '300px', height: '300px' }}
      loop
      autoplay={false}
    />
  );
};

export default LottieAnimation;

In this code, animationRef is used to reference the LottiePlayer component. The IntersectionObserver is set up to play the animation when at least 50% of it is visible in the viewport and stop it otherwise.

I hope the information may helps you.