How to embed Lottie in React
Lottie animations are just JSON files, so rendering one in React is mostly a matter of handing that JSON to a player and giving it a DOM node to draw into. There are two solid ways to do it: the low-level lottie-web library, which gives you full control over playback, and the lottie-react wrapper, which hides the boilerplate. This article covers both, plus the cleanup, SSR, and TypeScript details that trip people up.
Option 1: lottie-web directly
lottie-web is the reference player. You call lottie.loadAnimation() with a container element and your animation data, and it returns an animation instance you can control. Install it first:
npm install lottie-webThen wire it up inside a useEffect, with a ref for the container:
import { useEffect, useRef } from "react";
import lottie from "lottie-web";
import animationData from "./checkmark.json";
export default function Checkmark() {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!containerRef.current) return;
const animation = lottie.loadAnimation({
container: containerRef.current,
renderer: "svg",
loop: true,
autoplay: true,
animationData,
});
return () => animation.destroy();
}, []);
return <div ref={containerRef} style={{ width: 120, height: 120 }} />;
}A few things to note. The renderer is usually "svg": it is the sharpest option and the default for most use cases. "canvas" exists for performance-sensitive scenes with many shapes, and "html" is a legacy fallback you rarely need. The container div needs explicit dimensions — the SVG will fill whatever size you give it, so set width and height or it collapses to nothing.
Controlling playback
The animation instance returned by loadAnimation is your remote control. Keep it in a ref so event handlers can reach it:
const animationRef = useRef<ReturnType<typeof lottie.loadAnimation> | null>(null);
// inside useEffect, after loadAnimation:
animationRef.current = animation;
// anywhere in the component:
animationRef.current?.play();
animationRef.current?.pause();
animationRef.current?.setSpeed(1.5);
animationRef.current?.goToAndPlay(30, true); // jump to frame 30 and play
animationRef.current?.goToAndStop(0, true); // jump to frame 0 and holdThe second argument of goToAndPlay and goToAndStop is isFrame: pass true to address a frame number, or false to address a time in seconds. Common patterns include playing a one-shot success animation on a button click, pausing a loader when a request finishes, and driving progress from scroll position with goToAndStop(progress * totalFrames, true).
Cleanup: destroy on unmount
This is the step most often forgotten, and the one that causes the most bugs. A Lottie animation keeps a requestAnimationFrame loop running and holds references to DOM nodes. If the component unmounts without cleanup, the loop keeps running against a detached node, leaking memory and, in Strict Mode or fast navigation, stacking duplicate animations on remount. Always return a cleanup function from your effect:
useEffect(() => {
const animation = lottie.loadAnimation({ /* ... */ });
return () => animation.destroy();
}, []);destroy() stops the frame loop, removes event listeners, and clears the container. If you store the instance in a ref, set it to null in the same cleanup so handlers cannot call methods on a destroyed instance.
Option 2: lottie-react
If you do not need fine-grained control, lottie-react wraps lottie-web in a React component and handles the lifecycle for you. Install it alongside the player:
npm install lottie-react lottie-webimport Lottie from "lottie-react";
import animationData from "./checkmark.json";
export default function Checkmark() {
return <Lottie animationData={animationData} loop autoplay style={{ width: 120, height: 120 }} />;
}That is the whole component. For playback control, pass a ref via the lottieRef prop — note that it is lottieRef, not the usual ref — and you get the same animation instance back:
import { useRef } from "react";
import Lottie, { type LottieRefCurrentProps } from "lottie-react";
import animationData from "./checkmark.json";
export default function Checkmark() {
const lottieRef = useRef<LottieRefCurrentProps>(null);
return (
<>
<Lottie lottieRef={lottieRef} animationData={animationData} loop={false} autoplay={false} />
<button onClick={() => lottieRef.current?.play()}>Play</button>
<button onClick={() => lottieRef.current?.pause()}>Pause</button>
<button onClick={() => lottieRef.current?.setSpeed(2)}>2x speed</button>
</>
);
}The instance exposed through lottieRef supports the same methods as the raw player — play(), pause(), setSpeed(), goToAndPlay(), goToAndStop(), and destroy() — so you can start simple and reach for more control later without switching libraries.
SSR: dynamic import and "use client"
Lottie needs the DOM, so it cannot run during server-side rendering. In a Next.js App Router project, there are two things to get right.
First, any component that touches lottie-web must be a client component: put "use client" at the top of the file. Without it, the server will try to evaluate the player code and fail on missing browser globals.
Second, if you want to be extra safe — or if the animation data is large — load the player lazily with next/dynamic and ssr: false:
import dynamic from "next/dynamic";
const Checkmark = dynamic(() => import("./Checkmark"), { ssr: false });
export default function Page() {
return <Checkmark />;
}This keeps the player out of the server bundle entirely and out of the initial client bundle too, so the page loads before the animation code arrives. The animation data itself can also be fetched at runtime instead of imported statically, which keeps it out of the JavaScript bundle — worth doing for large files, especially ones with embedded raster frames. If your file is one of those, read why your Lottie file is 70 MB and run it through the lottie-mini compressor first.
TypeScript notes
- Importing JSON: with
resolveJsonModule: trueintsconfig.json(the Next.js default),import animationData from "./checkmark.json"is typed automatically. Without it, you will need a declaration file or afetch+JSON.parseinstead. - Typing the instance: the return type of
lottie.loadAnimation()isAnimationItem, exported fromlottie-web. Use it for refs instead ofany. - lottie-react types: the wrapper ships its own types, including
LottieRefCurrentPropsfor the ref andLottieComponentPropsfor the component props. - Animation data shape: if you type the JSON yourself, the top level is an object with
v,fr,ip,op,w,h,layers, andassets. In practice, importing the JSON and letting TypeScript infer the type is simpler and less error-prone.
Listening for events
Sometimes you need to react when an animation finishes — for example, to hide a success checkmark and show the next screen. The animation instance emits events you can subscribe to with addEventListener:
useEffect(() => {
const animation = lottie.loadAnimation({ /* ... */ });
const onComplete = () => {
console.log("Animation finished");
};
animation.addEventListener("complete", onComplete);
return () => {
animation.removeEventListener("complete", onComplete);
animation.destroy();
};
}, []);The complete event fires when a non-looping animation reaches its last frame. loopComplete fires at the end of each loop, and enterFramefires on every frame with the current frame number — handy for syncing something else to the animation’s progress. Remove listeners in the same cleanup where you call destroy(), so a remount does not stack duplicate handlers.
Playing a segment
A single animation file can hold several states — for example, frames 0–30 for an idle loop and frames 30–60 for a success burst. Instead of exporting two files, play just the segment you need with playSegments:
// Play only frames 30 to 60, then stop:
animation.playSegments([[30, 60]], true);
// Play just the first segment (repeats while loop is enabled):
animation.playSegments([[0, 30]], true);The first argument is an array of [startFrame, endFrame] pairs, and the second argument, forceFlag, tells the player to jump to the segment immediately instead of finishing the current frame first. This is how most button and state-transition animations are built: one file, several segments, and a small state machine in your component deciding which segment to play.
Loading animation data at runtime
Importing the JSON statically bundles it into your JavaScript, which is fine for a small icon but wasteful for a large animation. For anything over a few hundred kilobytes, fetch the file at runtime instead:
useEffect(() => {
let animation: ReturnType<typeof lottie.loadAnimation> | null = null;
fetch("/animations/hero.json")
.then((res) => res.json())
.then((animationData) => {
if (!containerRef.current) return;
animation = lottie.loadAnimation({
container: containerRef.current,
renderer: "svg",
loop: true,
autoplay: true,
animationData,
});
});
return () => animation?.destroy();
}, []);This keeps the animation out of the JavaScript bundle entirely, so the page becomes interactive before the animation data arrives. It also lets you serve the file from a CDN or swap it without redeploying the app. The same pattern works with lottie-react: fetch the JSON, store it in state, and render <Lottie> once the data is loaded.
Common pitfalls
- Strict Mode double-mount: in development, React 18+ mounts effects twice. Without a cleanup, you get two animations in one container — one more reason never to skip
destroy(). - Forgetting the container size: an empty
divhas zero height, and the animation renders into nothing. Always give the container explicit dimensions, or a CSS aspect ratio. - autoplay with loop set to false: a one-shot animation plays once and stops on its last frame. If the component mounts before the user can see it, the animation may already be over. Set
autoplay: falseand callplay()when the moment arrives. - Swapping animationData without remounting: changing the
animationDataprop does not reload the animation. If the data changes, either destroy and recreate the animation in an effect keyed on the data, or give the component akeyprop so React mounts a fresh instance.
Which option should you pick?
Reach for lottie-react when you want to drop an animation into a page and move on: it is less code, it handles mounting and cleanup, and the lottieRef escape hatch covers most control needs. Reach for lottie-web directly when you need event listeners (animation.addEventListener("complete", ...)), segment playback, multiple animations sharing one player instance, or anything else the wrapper does not expose. Either way, remember the three rules: size the container, destroy on unmount, and keep the player on the client. And if the animation file itself is heavy, compare formats in Lottie vs GIF vs MP4 — and consider whether the file should be a .lottie bundle instead, covered in dotLottie vs JSON.