diff --git a/lib/hooks/use-assert-singleton.ts b/lib/hooks/use-assert-singleton.ts new file mode 100644 index 0000000..f25849e --- /dev/null +++ b/lib/hooks/use-assert-singleton.ts @@ -0,0 +1,21 @@ +import { useEffect } from 'react'; + +const IDS = new Set(); + +/** + * Asserts that there is only one instance of a singleton entity. It can be a hook or a component. + * @param id The unique ID of the singleton entity. + */ +export function useAssertSingleton(id: string | symbol) { + useEffect(() => { + if (IDS.has(id)) { + throw new Error(`There should be only one instance of ${String(id)}`); + } + + IDS.add(id); + + return () => { + IDS.delete(id); + }; + }, [id]); +}