|
1 | 1 | /* eslint-disable import/no-unresolved */ |
2 | | -import { unstable_batchedUpdates } from 'react-dom'; |
| 2 | +import {unstable_batchedUpdates} from 'react-dom'; |
3 | 3 | import { |
4 | | - unstable_scheduleCallback as scheduleCallback, |
5 | | - unstable_ImmediatePriority as ImmediatePriority, |
| 4 | + unstable_scheduleCallback as scheduleCallback, |
| 5 | + unstable_ImmediatePriority as ImmediatePriority, |
6 | 6 | } from 'scheduler'; |
7 | 7 |
|
8 | 8 | import defaults from '../defaults'; |
9 | 9 | import supports from './supported-features'; |
10 | 10 |
|
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 | +} |
12 | 27 |
|
13 | 28 | 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); |
22 | 38 |
|
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 | + } |
31 | 43 | } |
0 commit comments