hookable icon indicating copy to clipboard operation
hookable copied to clipboard

`hookOnce` callback can fire twice when concurrent `callHook`s overlap behind an async hook

Open deepanshupal opened this issue 1 month ago • 0 comments

hookOnce unregisters its wrapper only when the wrapper first runs. callHookWith snapshots the hook list ([...this._hooks[name]]) before calling hooks, and when another hook ahead of the hookOnce callback is async, the first call's wrapper has not run yet by the time a second callHook starts. The second call's snapshot still contains the wrapper, and when it runs, _unreg is already undefined - but the user's callback is still captured, so it fires a second time.

Minimal reproduction (hookable 6.1.2 / main):

import { createHooks } from "hookable";

const hooks = createHooks();
let calls = 0;

// Any async hook registered before the hookOnce callback
hooks.hook("test", async () => {
  await new Promise((resolve) => setTimeout(resolve, 10));
});
hooks.hookOnce("test", () => {
  calls++;
});

await Promise.all([hooks.callHook("test"), hooks.callHook("test")]);

console.log(calls); // 2 - expected 1

The README documents hookOnce as "unregisters hook once called", so the callback should run at most once no matter how calls overlap.

deepanshupal avatar Oct 05 '26 01:10 deepanshupal