From ca10584ed422be62e9eea2b7d05007cd2abd3870 Mon Sep 17 00:00:00 2001 From: Hernan Torrisi Date: Fri, 13 Dec 2024 15:08:50 -0800 Subject: [PATCH] cleanup instance if use effect reruns and instance is not loaded --- src/hooks/useRive.tsx | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/hooks/useRive.tsx b/src/hooks/useRive.tsx index 70f4af3..3f79f2a 100644 --- a/src/hooks/useRive.tsx +++ b/src/hooks/useRive.tsx @@ -126,24 +126,32 @@ export default function useRive( if (!canvasElem || !riveParams) { return; } + let isLoaded = rive != null; + let r: Rive | null; if (rive == null) { const { useOffscreenRenderer } = options; - const r = new Rive({ + r = new Rive({ useOffscreenRenderer, ...riveParams, canvas: canvasElem, }); r.on(EventType.Load, () => { + isLoaded = true; // Check if the component/canvas is mounted before setting state to avoid setState // on an unmounted component in some rare cases if (canvasElem) { setRive(r); } else { // If unmounted, cleanup the rive object immediately - r.cleanup(); + r!.cleanup(); } }); } + return () => { + if(!isLoaded) { + r?.cleanup(); + } + } }, [canvasElem, isParamsLoaded, rive]); /** * Ref callback called when the container element mounts