patrick-ts
patrick-ts

Reputation: 81

Animation in lottie crashes my react application

I'm developing an application in React, the project was created with Vite.

I tried to implement an animation with Lottie and I succeeded, however, when I change the page (my application has 4 pages) where the animation is and I go back to that page, my site crashes.

I don't know what the problem is because it's my first time using Lottie in a project, any help is welcome.

Here is an example of a component that contains the animation:

import { useLottie } from "lottie-react";

import devAnimationData from "../../assets/lottie/dev-animation.json";

export const Developer = () => {
  const styles = {
    height: 500,
    width: 500
  };

  const defaultOptions = {
    loop: true,
    autoplay: true,
    animationData: devAnimationData,
    rendererSettings: {
      preserveAspectRatio: "xMidYMid slice"
    }
  };
  const { View } = useLottie(defaultOptions, styles);
  return View;
};

Upvotes: 4

Views: 1856

Answers (1)

yem
yem

Reputation: 755

I came across the same issue and after doing some research online I came across this question in Github.

It seems like for some animations you may be loading the same animation object twice and this causes nested repeaters.

I followed the instructions given in bodymovin's comment and that seemed to fix the issue for me.

Instead of simply having animationData set the way you did I'd do the following:

animationData: JSON.parse(JSON.stringify(devAnimationData))

Let me know if this solves your problem.

The comment that I referenced to solve my issue:

I guess animationData is being imported somewhere and passed down to this component every time you load an animation. If you pass the same animationData several times, you are passing the same object, and Lottie uses and modifies that object every time it loads a new animation. Repeatears, because of the way they work, create this type of nested elements and spike on memory. You probably should pass the animation data down by doing JSON.parse(JSON.stringify(animationData )) and it will work fine.

Upvotes: 8

Related Questions