Skip to content

Commit

Permalink
Aggregate updates using addStatusHandler and Promise.resolve instead …
Browse files Browse the repository at this point in the history
…of setTimeout
  • Loading branch information
alexkirsz committed Nov 3, 2022
1 parent 4af5011 commit 71efaf4
Showing 1 changed file with 30 additions and 15 deletions.
45 changes: 30 additions & 15 deletions packages/react-refresh-utils/internal/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,23 @@

import RefreshRuntime from 'react-refresh/runtime'

type ModuleHotStatus =
| 'idle'
| 'check'
| 'prepare'
| 'ready'
| 'dispose'
| 'apply'
| 'abort'
| 'fail'

type ModuleHotStatusHandler = (status: ModuleHotStatus) => void

declare const module: {
hot: {
status: () =>
| 'idle'
| 'check'
| 'prepare'
| 'ready'
| 'dispose'
| 'apply'
| 'abort'
| 'fail'
status: () => ModuleHotStatus
addStatusHandler: (handler: ModuleHotStatusHandler) => void
removeStatusHandler: (handler: ModuleHotStatusHandler) => void
}
}

Expand Down Expand Up @@ -133,21 +139,30 @@ function shouldInvalidateReactRefreshBoundary(
}

var isUpdateScheduled: boolean = false
// This function aggregates updates from multiple modules into a single React Refresh call.
function scheduleUpdate() {
if (isUpdateScheduled) {
return
}

function canApplyUpdate() {
return module.hot.status() === 'idle'
function canApplyUpdate(status: ModuleHotStatus) {
return status === 'idle'
}

let applyUpdate = canApplyUpdate(module.hot.status())

const statusHandler = (status) => {
applyUpdate = canApplyUpdate(status)
}

module.hot.addStatusHandler(statusHandler)

isUpdateScheduled = true
setTimeout(function () {
Promise.resolve().then(() => {
isUpdateScheduled = false
module.hot.removeStatusHandler(statusHandler)

// Only trigger refresh if the webpack HMR state is idle
if (canApplyUpdate()) {
if (applyUpdate) {
try {
RefreshRuntime.performReactRefresh()
} catch (err) {
Expand All @@ -160,7 +175,7 @@ function scheduleUpdate() {
}

return scheduleUpdate()
}, 30)
})
}

// Needs to be compatible with IE11
Expand Down

0 comments on commit 71efaf4

Please sign in to comment.