From 87e5dfb52a84869d62b6343887a1c8659aee595d Mon Sep 17 00:00:00 2001 From: Michel Weststrate Date: Mon, 25 Sep 2023 12:27:42 +0100 Subject: [PATCH] Fix: disable global state version usage in observer. Fixes #3728 (#3763) * fix: disable global state version usage to avoid footgun with fresh props not propagationg, fixes #3728 * chore: Added changeset * clean up forceUpdate --- .changeset/light-birds-grow.md | 5 +++++ packages/mobx-react-lite/src/useObserver.ts | 20 +++++--------------- 2 files changed, 10 insertions(+), 15 deletions(-) create mode 100644 .changeset/light-birds-grow.md diff --git a/.changeset/light-birds-grow.md b/.changeset/light-birds-grow.md new file mode 100644 index 000000000..b001bd2cc --- /dev/null +++ b/.changeset/light-birds-grow.md @@ -0,0 +1,5 @@ +--- +"mobx-react-lite": patch +--- + +Switched observer implementation from using global to local state version. Fixes #3728 diff --git a/packages/mobx-react-lite/src/useObserver.ts b/packages/mobx-react-lite/src/useObserver.ts index 5c7e2ea6d..8bc07b360 100644 --- a/packages/mobx-react-lite/src/useObserver.ts +++ b/packages/mobx-react-lite/src/useObserver.ts @@ -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" @@ -24,15 +24,9 @@ type ObserverAdministration = { getSnapshot: Parameters[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. @@ -47,9 +41,6 @@ export function useObserver(render: () => T, baseComponentName: string = "obs const admRef = React.useRef(null) - // Provides ability to force component update without changing state version - const [, forceUpdate] = React.useState() - if (!admRef.current) { // First render const adm: ObserverAdministration = { @@ -69,7 +60,8 @@ export function useObserver(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 () => { @@ -81,9 +73,7 @@ export function useObserver(render: () => T, baseComponentName: string = "obs }, getSnapshot() { // Do NOT access admRef here! - return globalStateVersionIsAvailable - ? _getGlobalState().stateVersion - : adm.stateVersion + return adm.stateVersion } }