-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
revamp batching implementation to batch in longer sequences
- Loading branch information
Showing
1 changed file
with
32 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,43 @@ | ||
/* eslint-disable import/no-unresolved */ | ||
import { unstable_batchedUpdates } from 'react-dom'; | ||
import {unstable_batchedUpdates} from 'react-dom'; | ||
import { | ||
unstable_scheduleCallback as scheduleCallback, | ||
unstable_ImmediatePriority as ImmediatePriority, | ||
unstable_scheduleCallback as scheduleCallback, | ||
unstable_ImmediatePriority as ImmediatePriority, | ||
} from 'scheduler'; | ||
|
||
import defaults from '../defaults'; | ||
import supports from './supported-features'; | ||
|
||
let isInsideBatchedSchedule = 0; | ||
let batchedScheduled = false; | ||
|
||
let batched = []; | ||
|
||
const executeBatched = () => { | ||
unstable_batchedUpdates(() => { | ||
while (batched.length) { | ||
const currentBatched = batched; | ||
batched = []; | ||
currentBatched.forEach(fn => fn()); | ||
} | ||
// important to reset it before exiting this function | ||
// as React will dump everything right after | ||
batchedScheduled = false; | ||
}); | ||
} | ||
|
||
export function batch(fn) { | ||
// if we are in node/tests or nested schedule | ||
if ( | ||
!defaults.batchUpdates || | ||
!supports.scheduling() || | ||
isInsideBatchedSchedule | ||
) { | ||
return unstable_batchedUpdates(fn); | ||
} | ||
// if we are in node/tests or nested schedule | ||
if ( | ||
!defaults.batchUpdates || | ||
!supports.scheduling() | ||
) { | ||
return unstable_batchedUpdates(fn); | ||
} | ||
|
||
batched.push(fn); | ||
|
||
isInsideBatchedSchedule = 0; | ||
// Use ImmediatePriority as it has -1ms timeout | ||
// https://github.com/facebook/react/blob/main/packages/scheduler/src/forks/Scheduler.js#L65 | ||
return scheduleCallback(ImmediatePriority, function scheduleBatchedUpdates() { | ||
isInsideBatchedSchedule++; | ||
unstable_batchedUpdates(fn); | ||
isInsideBatchedSchedule--; | ||
}); | ||
if (!batchedScheduled) { | ||
batchedScheduled = true; | ||
return scheduleCallback(ImmediatePriority, executeBatched); | ||
} | ||
} |