MCPcopy Index your code
hub / github.com/mobxjs/mobx / useObserver

Function useObserver

packages/mobx-react-lite/src/useObserver.ts:35–119  ·  view source on GitHub ↗
(render: () => T, baseComponentName: string = "observed")

Source from the content-addressed store, hash-verified

33}
34
35export function useObserver<T>(render: () => T, baseComponentName: string = "observed"): T {
36 if (isUsingStaticRendering()) {
37 return render()
38 }
39
40 const admRef = React.useRef<ObserverAdministration | null>(null)
41
42 if (!admRef.current) {
43 // First render
44 const adm: ObserverAdministration = {
45 reaction: null,
46 onStoreChange: null,
47 stateVersion: Symbol(),
48 name: baseComponentName,
49 subscribe(onStoreChange: () => void) {
50 // Do NOT access admRef here!
51 observerFinalizationRegistry.unregister(adm)
52 adm.onStoreChange = onStoreChange
53 if (!adm.reaction) {
54 // We've lost our reaction and therefore all subscriptions, occurs when:
55 // 1. Timer based finalization registry disposed reaction before component mounted.
56 // 2. React "re-mounts" same component without calling render in between (typically <StrictMode>).
57 // We have to recreate reaction and schedule re-render to recreate subscriptions,
58 // even if state did not change.
59 createReaction(adm)
60 // `onStoreChange` won't force update if subsequent `getSnapshot` returns same value.
61 // So we make sure that is not the case
62 adm.stateVersion = Symbol()
63 }
64
65 return () => {
66 // Do NOT access admRef here!
67 adm.onStoreChange = null
68 adm.reaction?.dispose()
69 adm.reaction = null
70 }
71 },
72 getSnapshot() {
73 // Do NOT access admRef here!
74 return adm.stateVersion
75 }
76 }
77
78 admRef.current = adm
79 }
80
81 const adm = admRef.current!
82
83 if (!adm.reaction) {
84 // First render or reaction was disposed by registry before subscribe
85 createReaction(adm)
86 // StrictMode/ConcurrentMode/Suspense may mean that our component is
87 // rendered and abandoned multiple times, so we need to track leaked
88 // Reactions.
89 observerFinalizationRegistry.register(admRef, adm, adm)
90 }
91
92 React.useDebugValue(adm.reaction!, printDebugValue)

Callers 9

ObserverComponentFunction · 0.90
observerComponentFunction · 0.90
CounterFunction · 0.90
CounterFunction · 0.90
TestComponentFunction · 0.90
TestComponent1Function · 0.90
TestComponent2Function · 0.90
TestComponent1Function · 0.90
TestComponent2Function · 0.90

Calls 4

isUsingStaticRenderingFunction · 0.90
registerMethod · 0.80
trackMethod · 0.80
createReactionFunction · 0.70

Tested by 7

CounterFunction · 0.72
CounterFunction · 0.72
TestComponentFunction · 0.72
TestComponent1Function · 0.72
TestComponent2Function · 0.72
TestComponent1Function · 0.72
TestComponent2Function · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…