Skip to content

Commit

Permalink
Fix: disable global state version usage in observer. Fixes #3728 (#3763)
Browse files Browse the repository at this point in the history
* fix: disable global state version usage to avoid footgun with fresh props not propagationg, fixes #3728

* chore: Added changeset

* clean up forceUpdate
  • Loading branch information
mweststrate committed Sep 25, 2023
1 parent 91adf79 commit 87e5dfb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/light-birds-grow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mobx-react-lite": patch
---

Switched observer implementation from using global to local state version. Fixes #3728
20 changes: 5 additions & 15 deletions packages/mobx-react-lite/src/useObserver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Reaction, _getGlobalState } from "mobx"
import { Reaction } from "mobx"
import React from "react"
import { printDebugValue } from "./utils/printDebugValue"
import { isUsingStaticRendering } from "./staticRendering"
Expand All @@ -24,15 +24,9 @@ type ObserverAdministration = {
getSnapshot: Parameters<typeof React.useSyncExternalStore>[1]
}

// BC
const globalStateVersionIsAvailable = typeof _getGlobalState().stateVersion !== "undefined"

function createReaction(adm: ObserverAdministration) {
adm.reaction = new Reaction(`observer${adm.name}`, () => {
if (!globalStateVersionIsAvailable) {
// BC
adm.stateVersion = Symbol()
}
adm.stateVersion = Symbol()
// onStoreChange won't be available until the component "mounts".
// If state changes in between initial render and mount,
// `useSyncExternalStore` should handle that by checking the state version and issuing update.
Expand All @@ -47,9 +41,6 @@ export function useObserver<T>(render: () => T, baseComponentName: string = "obs

const admRef = React.useRef<ObserverAdministration | null>(null)

// Provides ability to force component update without changing state version
const [, forceUpdate] = React.useState<Symbol>()

if (!admRef.current) {
// First render
const adm: ObserverAdministration = {
Expand All @@ -69,7 +60,8 @@ export function useObserver<T>(render: () => T, baseComponentName: string = "obs
// even if state did not change.
createReaction(adm)
// `onStoreChange` won't force update if subsequent `getSnapshot` returns same value.
forceUpdate(Symbol())
// So we make sure that is not the case
adm.stateVersion = Symbol()
}

return () => {
Expand All @@ -81,9 +73,7 @@ export function useObserver<T>(render: () => T, baseComponentName: string = "obs
},
getSnapshot() {
// Do NOT access admRef here!
return globalStateVersionIsAvailable
? _getGlobalState().stateVersion
: adm.stateVersion
return adm.stateVersion
}
}

Expand Down

0 comments on commit 87e5dfb

Please sign in to comment.