Skip to content

Commit 8a7f08d

Browse files
committed
revamp batching implementation to batch in longer sequences
1 parent 4b0c136 commit 8a7f08d

File tree

1 file changed

+32
-20
lines changed

1 file changed

+32
-20
lines changed

src/utils/batched-updates.js

Lines changed: 32 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,43 @@
11
/* eslint-disable import/no-unresolved */
2-
import { unstable_batchedUpdates } from 'react-dom';
2+
import {unstable_batchedUpdates} from 'react-dom';
33
import {
4-
unstable_scheduleCallback as scheduleCallback,
5-
unstable_ImmediatePriority as ImmediatePriority,
4+
unstable_scheduleCallback as scheduleCallback,
5+
unstable_ImmediatePriority as ImmediatePriority,
66
} from 'scheduler';
77

88
import defaults from '../defaults';
99
import supports from './supported-features';
1010

11-
let isInsideBatchedSchedule = 0;
11+
let batchedScheduled = false;
12+
13+
let batched = [];
14+
15+
const executeBatched = () => {
16+
unstable_batchedUpdates(() => {
17+
while (batched.length) {
18+
const currentBatched = batched;
19+
batched = [];
20+
currentBatched.forEach(fn => fn());
21+
}
22+
// important to reset it before exiting this function
23+
// as React will dump everything right after
24+
batchedScheduled = false;
25+
});
26+
}
1227

1328
export function batch(fn) {
14-
// if we are in node/tests or nested schedule
15-
if (
16-
!defaults.batchUpdates ||
17-
!supports.scheduling() ||
18-
isInsideBatchedSchedule
19-
) {
20-
return unstable_batchedUpdates(fn);
21-
}
29+
// if we are in node/tests or nested schedule
30+
if (
31+
!defaults.batchUpdates ||
32+
!supports.scheduling()
33+
) {
34+
return unstable_batchedUpdates(fn);
35+
}
36+
37+
batched.push(fn);
2238

23-
isInsideBatchedSchedule = 0;
24-
// Use ImmediatePriority as it has -1ms timeout
25-
// https://github.com/facebook/react/blob/main/packages/scheduler/src/forks/Scheduler.js#L65
26-
return scheduleCallback(ImmediatePriority, function scheduleBatchedUpdates() {
27-
isInsideBatchedSchedule++;
28-
unstable_batchedUpdates(fn);
29-
isInsideBatchedSchedule--;
30-
});
39+
if (!batchedScheduled) {
40+
batchedScheduled = true;
41+
return scheduleCallback(ImmediatePriority, executeBatched);
42+
}
3143
}

0 commit comments

Comments
 (0)