Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/pdfium-engine-strict-mode-guard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@embedpdf/engines': patch
---

fix(engines): `usePdfiumEngine` now discards the engine it created if the effect was torn down before init resolved, instead of committing it. This stops React Strict Mode's dev remount from creating two engines, remounting engine-keyed consumers (e.g. `<EmbedPDF>`) mid-load, and leaking the first engine. Engine teardown also captures its target locally so a `wasmUrl` change mid-init can no longer destroy the replacement engine.
20 changes: 16 additions & 4 deletions packages/engines/src/shared/hooks/use-pdfium-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ interface UsePdfiumEngineProps {
fontFallback?: FontFallbackConfig | null;
}

function disposeEngine(engine: PdfEngine | null) {
engine?.closeAllDocuments?.().wait(() => {
engine?.destroy?.();
}, ignore);
}

export function usePdfiumEngine(config?: UsePdfiumEngineProps) {
const {
wasmUrl = defaultWasmUrl,
Expand Down Expand Up @@ -44,6 +50,14 @@ export function usePdfiumEngine(config?: UsePdfiumEngineProps) {
encoderPoolSize,
fontFallback,
});

// Effect torn down before we resolved (e.g. Strict Mode's dev
// remount): discard this engine instead of committing it.
if (cancelled) {
disposeEngine(pdfEngine);
return;
}

engineRef.current = pdfEngine;
setEngine(pdfEngine);
setLoading(false);
Expand All @@ -57,10 +71,8 @@ export function usePdfiumEngine(config?: UsePdfiumEngineProps) {

return () => {
cancelled = true;
engineRef.current?.closeAllDocuments?.().wait(() => {
engineRef.current?.destroy?.();
engineRef.current = null;
}, ignore);
disposeEngine(engineRef.current);
engineRef.current = null;
};
}, [wasmUrl, worker, logger, fontFallback]);

Expand Down