Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/optional-react-dom-batching.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mobx-react-lite": patch
---

Avoid requiring optional `react-dom` during module initialization and fall back to no-op batching when it is unavailable.
15 changes: 15 additions & 0 deletions packages/mobx-react-lite/__tests__/optionalReactDom.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
afterEach(() => {
jest.dontMock("react-dom")
jest.resetModules()
})

test("does not fail to load when react-dom is unavailable", () => {
jest.resetModules()
jest.doMock("react-dom", () => {
throw Object.assign(new Error("Cannot find module 'react-dom'"), {
code: "MODULE_NOT_FOUND"
})
})

expect(() => require("../src/index.ts")).not.toThrow()
})
20 changes: 19 additions & 1 deletion packages/mobx-react-lite/src/utils/reactBatchedUpdates.ts
Original file line number Diff line number Diff line change
@@ -1 +1,19 @@
export { unstable_batchedUpdates } from "react-dom"
import { defaultNoopBatch } from "./observerBatching"

declare const require:
| ((moduleName: string) => { unstable_batchedUpdates?: typeof defaultNoopBatch })
| undefined

export let unstable_batchedUpdates = defaultNoopBatch

if (typeof require === "function") {
try {
const reactDom = require("react-dom")
if (reactDom.unstable_batchedUpdates) {
unstable_batchedUpdates = reactDom.unstable_batchedUpdates
}
} catch {
// react-dom is optional. React 18+ batches updates automatically, so fall back to no-op
// batching when react-dom isn't available (for example in React Native or server-only installs).
}
}