lottie files reducing performance on NextJS app

Viewed 4835

I am using lottie JSON files on my NextJS project to show some of these cool animations.

The problem is the lottie JSON files are huge and really decrease the performance of the app. Has anyone found a way to use a handful of these animations without halving the performance score of their project?

I am using them on my personal website(link below) and the lottie files are located on the services section(if you scroll a bit below). The initial page load feels a bit slow and I would really like to find a solution to this.

https://stylidis.io

2 Answers

You can load the library and the animation json asynchronously (dynamically), like that:

import { useEffect, useRef, useState } from 'react';
import type { LottiePlayer } from 'lottie-web';


export const Animation = () => {
  const ref = useRef<HTMLDivElement>(null);
  const [lottie, setLottie] = useState<LottiePlayer | null>(null);

  useEffect(() => {
    import('lottie-web').then((Lottie) => setLottie(Lottie.default));
  }, []);

  useEffect(() => {
    if (lottie && ref.current) {
      const animation = lottie.loadAnimation({
        container: ref.current,
        renderer: 'svg',
        loop: true,
        autoplay: true,
        // path to your animation file, place it inside public folder
        path: '/animation.json',
      });

      return () => animation.destroy();
    }
  }, [lottie]);

  return (
    <div ref={ref} />
  );
};

First install your package npm install --save @lottiefiles/lottie-player or simply yarn add @lottiefiles/lottie-player

import React, { FC, useEffect, useRef } from 'react';


const YourCard: FC = () => {
    const ref = useRef(null);
    useEffect(() => {
        import('@lottiefiles/lottie-player');
    });
    return (
        <div>
             <lottie-player
                    id="firstLottie"
                    ref={ref}
                    autoplay
                    mode="normal"
                    src="here your json link/find on lottie website"
                />
            
        </div>
    );
};
export default YourCard;

Do add a declaration file named declaration.d.ts to the root of the project as well

declare namespace JSX {
  interface IntrinsicElements {
    "lottie-player": any;
  }
}
Related