fix(jsx): handle useSyncExternalStore subscription and snapshot changes (#5166)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(jsx): resubscribe when the external store changes Refresh the snapshot after attaching the new subscription so switching stores does not leave stale state behind. * fix(jsx): read external store snapshot during render * fix(jsx): use latest snapshot when subscribing * fix(jsx): keep the old subscription until resubscribing at effect flush
authored by Taku Amano · committed by GitHub · parent df653ce · Browse files · 2 files·+145 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+145 added−13 removed
- tests:+126 added−2 removed
- other:+19 added−11 removed
Provenance
- Commit
224d2f5- Tree
b289c49- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
df653ce
2 files changed+145 added−13 removed
modified:src/jsx/hooks/dom.test.tsx+126 added-2 removed
11 unmodified lines12 useDebugValue,13 useDeferredValue,14 useId,15 useImperativeHandle,16+ useLayoutEffect,17 useReducer,18 useState,19 useSyncExternalStore,20 useTransition,653 unmodified lines674 it('simple', async () => {675 let count = 0676 const unsubscribe = vi.fn()677 const subscribe = vi.fn(() => unsubscribe)677- const getSnapshot = vi.fn(() => count++)678+ const getSnapshot = vi.fn(() => count)679 const SubApp = () => {680 const count = useSyncExternalStore(subscribe, getSnapshot)681 return <div>{count}</div>682 }12 unmodified lines695 root.querySelector('button')?.click()696 await new Promise((r) => setTimeout(r))697 expect(root.innerHTML).toBe('<button>toggle</button>')698 expect(unsubscribe).toBeCalled()699+ count = 1700 root.querySelector('button')?.click()701 await new Promise((r) => setTimeout(r))702 expect(root.innerHTML).toBe('<div>1</div><button>toggle</button>')703 })704 705+ it('updates the snapshot when subscribe changes', async () => {706+ const unsubscribeA = vi.fn()707+ const subscribeA = vi.fn(() => unsubscribeA)708+ const unsubscribeB = vi.fn()709+ const subscribeB = vi.fn(() => unsubscribeB)710+ const stores = [711+ { subscribe: subscribeA, getSnapshot: () => 'a1' },712+ { subscribe: subscribeB, getSnapshot: () => 'b0' },713+ ]714+715+ const App = () => {716+ const [index, setIndex] = useState(0)717+ const store = stores[index]718+ const value = useSyncExternalStore(store.subscribe, store.getSnapshot)719+ return <button onClick={() => setIndex(1)}>{value}</button>720+ }721+722+ render(<App />, root)723+ await new Promise((r) => setTimeout(r))724+ expect(root.innerHTML).toBe('<button>a1</button>')725+ expect(subscribeA).toBeCalledTimes(1)726+727+ root.querySelector('button')?.click()728+ await Promise.resolve()729+ expect(root.innerHTML).toBe('<button>b0</button>')730+ // the old store stays subscribed until the new subscription is set up at effect flush731+ expect(unsubscribeA).not.toBeCalled()732+ await new Promise((r) => setTimeout(r))733+ expect(unsubscribeA).toBeCalledTimes(1)734+ expect(subscribeB).toBeCalledTimes(1)735+ expect(unsubscribeB).not.toBeCalled()736+ })737+738+ it('updates the snapshot when getSnapshot changes', async () => {739+ const state: Record<string, string> = { a: 'a0', b: 'b0' }740+ const listeners = new Set<() => void>()741+ const subscribe = vi.fn((listener: () => void) => {742+ listeners.add(listener)743+ return () => listeners.delete(listener)744+ })745+746+ const App = () => {747+ const [key, setKey] = useState('a')748+ const value = useSyncExternalStore(subscribe, () => state[key])749+ return <button onClick={() => setKey('b')}>{value}</button>750+ }751+752+ render(<App />, root)753+ await new Promise((r) => setTimeout(r))754+ expect(root.innerHTML).toBe('<button>a0</button>')755+ expect(subscribe).toBeCalledTimes(1)756+757+ root.querySelector('button')?.click()758+ await new Promise((r) => setTimeout(r))759+ expect(root.innerHTML).toBe('<button>b0</button>')760+ expect(subscribe).toBeCalledTimes(1)761+762+ state.b = 'b1'763+ listeners.forEach((listener) => listener())764+ await new Promise((r) => setTimeout(r))765+ expect(root.innerHTML).toBe('<button>b1</button>')766+ })767+768+ it('uses the latest getSnapshot when subscribing after a layout effect update', async () => {769+ const state = { a: 'a0', b: 'b0' }770+ const subscribe = vi.fn((_listener: () => void) => vi.fn())771+772+ const App = () => {773+ const [key, setKey] = useState<keyof typeof state>('a')774+ const value = useSyncExternalStore(subscribe, () => state[key])775+776+ useLayoutEffect(() => {777+ setKey('b')778+ queueMicrotask(() => {779+ state.b = 'b1'780+ })781+ }, [])782+783+ return <div>{value}</div>784+ }785+786+ render(<App />, root)787+ expect(root.innerHTML).toBe('<div>a0</div>')788+789+ await new Promise((r) => setTimeout(r))790+ expect(root.innerHTML).toBe('<div>b1</div>')791+ })792+793+ it('does not loop when subscribe changes on every render', async () => {794+ const unsubscribes: ReturnType<typeof vi.fn>[] = []795+ const subscribe = vi.fn((_listener: () => void) => {796+ const unsubscribe = vi.fn()797+ unsubscribes.push(unsubscribe)798+ return unsubscribe799+ })800+ const getSnapshot = () => 'snapshot'801+ let renderCount = 0802+803+ const App = () => {804+ const [count, setCount] = useState(0)805+ renderCount++806+ const value = useSyncExternalStore((listener) => subscribe(listener), getSnapshot)807+ return <button onClick={() => setCount((count) => count + 1)}>{`${value}:${count}`}</button>808+ }809+810+ render(<App />, root)811+ await new Promise((r) => setTimeout(r))812+ expect(root.innerHTML).toBe('<button>snapshot:0</button>')813+ expect(renderCount).toBe(1)814+ expect(subscribe).toBeCalledTimes(1)815+816+ root.querySelector('button')?.click()817+ await Promise.resolve()818+ await new Promise((r) => setTimeout(r))819+ expect(root.innerHTML).toBe('<button>snapshot:1</button>')820+ expect(renderCount).toBe(2)821+ expect(subscribe).toBeCalledTimes(2)822+ expect(unsubscribes[0]).toBeCalledTimes(1)823+ expect(unsubscribes[1]).not.toBeCalled()824+ })825+826 it('with getServerSnapshot', async () => {827 let count = 0828 const unsubscribe = vi.fn()829 const subscribe = vi.fn(() => unsubscribe)707- const getSnapshot = vi.fn(() => count++)830+ const getSnapshot = vi.fn(() => count)831 const getServerSnapshot = vi.fn(() => 100)832 const SubApp = () => {833 const count = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)834 return <div>{count}</div>14 unmodified lines849 root.querySelector('button')?.click()850 await new Promise((r) => setTimeout(r))851 expect(root.innerHTML).toBe('<button>toggle</button>')852 expect(unsubscribe).toBeCalled()853+ count = 1854 root.querySelector('button')?.click()855 await new Promise((r) => setTimeout(r))856 expect(root.innerHTML).toBe('<div>1</div><button>toggle</button>')857 })2 unmodified linesmodified:src/jsx/hooks/index.ts+19 added-11 removed
406 unmodified lines407 }408 return getServerSnapshot()409 }410 411- const [serverSnapshotIsUsed] = useState<boolean>(!!(buildData[0][4] && getServerSnapshot))412- const [state, setState] = useState(() =>413- serverSnapshotIsUsed ? (getServerSnapshot as () => T)() : getSnapshot()414- )411+ const snapshot =412+ buildData[0][4] && getServerSnapshot ? (getServerSnapshot as () => T)() : getSnapshot()413+ const [, setVersion] = useState(0)414+ const latestSnapshot = useRef<[T, () => T]>([snapshot, getSnapshot])415+ latestSnapshot.current = [snapshot, getSnapshot]416+ const unsubscribeRef = useRef<() => void>(null)417+418+ // Swap subscriptions at effect flush: a returned cleanup would run synchronously419+ // during render when `subscribe` changes, leaving a window with no subscription.420 useEffect(() => {416- if (serverSnapshotIsUsed) {417- setState(getSnapshot())421+ const update = () => setVersion((version) => version + 1)422+ unsubscribeRef.current?.()423+ unsubscribeRef.current = subscribe(update)424+ const [snapshot, getSnapshot] = latestSnapshot.current!425+ if (!Object.is(snapshot, getSnapshot())) {426+ update()427 }419- return subscribe(() => {420- setState(getSnapshot())421- })422- }, [])428+ }, [subscribe])429 424- return state430+ useEffect(() => () => unsubscribeRef.current?.(), [])431+432+ return snapshot433 }