Skip to content

Commit 2d647bf

Browse files
committed
extract flushMicrotask as a helper, improve implementation
1 parent 768626e commit 2d647bf

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

packages/react-components/src/renderers/useRenderer.ts

+1-16
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
} from 'react';
1010
import { createPortal, flushSync } from 'react-dom';
1111
import type { Slice, WebComponentRenderer } from './renderer.js';
12+
import { flushMicrotask } from '../utils/flushMicrotask.js';
1213

1314
export type UseRendererResult<W extends WebComponentRenderer> = readonly [
1415
portals?: ReadonlyArray<ReactElement | null>,
@@ -28,22 +29,6 @@ export type RendererConfig = {
2829
renderMode?: 'default' | 'sync' | 'microtask';
2930
};
3031

31-
const renderQueue: Array<(...args: any[]) => any> = [];
32-
33-
function flushMicrotask(callback: (...args: any[]) => any) {
34-
renderQueue.push(callback);
35-
36-
if (renderQueue.length === 1) {
37-
queueMicrotask(() => {
38-
flushSync(() => {
39-
while (renderQueue.length) {
40-
renderQueue.shift()!();
41-
}
42-
});
43-
});
44-
}
45-
}
46-
4732
export function useRenderer<P extends {}, W extends WebComponentRenderer>(
4833
node: ReactNode,
4934
convert?: (props: Slice<Parameters<W>, 1>) => PropsWithChildren<P>,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { flushSync } from 'react-dom';
2+
3+
let callbackQueue: Function[] = [];
4+
5+
export function flushMicrotask(callback: Function) {
6+
callbackQueue.push(callback);
7+
8+
if (callbackQueue.length === 1) {
9+
queueMicrotask(() => {
10+
const queue = callbackQueue;
11+
callbackQueue = [];
12+
13+
flushSync(() => {
14+
queue.forEach((callback) => callback());
15+
});
16+
});
17+
}
18+
}

0 commit comments

Comments
 (0)