Skip to content

Commit 5519fb2

Browse files
committed
cleanup instance if use effect reruns and instance is not loaded
1 parent a088564 commit 5519fb2

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/hooks/useRive.tsx

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,24 +126,32 @@ export default function useRive(
126126
if (!canvasElem || !riveParams) {
127127
return;
128128
}
129+
let isLoaded = rive != null;
130+
let r: Rive | null;
129131
if (rive == null) {
130132
const { useOffscreenRenderer } = options;
131-
const r = new Rive({
133+
r = new Rive({
132134
useOffscreenRenderer,
133135
...riveParams,
134136
canvas: canvasElem,
135137
});
136138
r.on(EventType.Load, () => {
139+
isLoaded = true;
137140
// Check if the component/canvas is mounted before setting state to avoid setState
138141
// on an unmounted component in some rare cases
139142
if (canvasElem) {
140143
setRive(r);
141144
} else {
142145
// If unmounted, cleanup the rive object immediately
143-
r.cleanup();
146+
r!.cleanup();
144147
}
145148
});
146149
}
150+
return () => {
151+
if(!isLoaded) {
152+
r?.cleanup();
153+
}
154+
}
147155
}, [canvasElem, isParamsLoaded, rive]);
148156
/**
149157
* Ref callback called when the container element mounts

0 commit comments

Comments
 (0)