(render: () => T, baseComponentName: string = "observed")
| 33 | } |
| 34 | |
| 35 | export 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) |
searching dependent graphs…