react-rx-hook-audit
GitHub用于审查和重构 React-rx Hook(如 useObservable)调用,识别因 observable 身份变化导致的多余重渲染或加载闪烁问题,并提供修复方案。
Trigger Scenarios
Install
npx skills add sanity-io/sanity --skill react-rx-hook-audit -g -y
SKILL.md
Frontmatter
{
"name": "react-rx-hook-audit",
"description": "Find react-rx hook call sites (useObservable, useSyncObservable, useObservablePromise) whose observable identity churns or that re-render more than needed, verify the suspicion at runtime, and refactor them to the useValuePreview pattern. Use when reviewing or writing a component or hook that calls these hooks, or when a re-render, loading flash or resubscribe storm is suspected."
}
react-rx hook audit
Start here
Use when a component or hook calls useObservable, useSyncObservable or useObservablePromise,
or when you suspect a re-render, loading flash or resubscribe storm.
Read the reference refactor packages/sanity/src/core/preview/useValuePreview.ts and its test
packages/sanity/src/core/preview/__test__/useValuePreview.test.tsx before you change a hook.
react-rx keeps one shared store per observable identity. A new identity is a new store and a new subscription of the source on commit, even when the pipeline is the same.
- react-rx 7 (installed since #14643) has no warm-up. Every identity change renders
initialValueonce and resubscribes on commit, so identity churn shows up as loading flashes.initialValueis required and omitting it throws during render.useObservableSubjectreplacesuseObservableEvent. - react-rx 6 subscribed a replacement observable once during render (
needsWarmUpandwarmUpin itsdist/index.js,npm pack react-rx@6.0.1to read them), so a synchronous emission showed in that render and the churn cost only the resubscribe. Code that looked fine on 6 flashes on 7.
Find candidates
# run from the repo root; every call site (120 files at the time of writing)
rg -n "use(Sync)?Observable(Promise)?\(" packages/sanity/src packages/@sanity/vision/src -g '!**/*.test.*' -g '!**/__test*__/**'
# calls without an initialValue (28 hits; react-rx 7 throws on these)
rg -nU "use(Sync)?Observable\(\s*[^,()]+?\s*\)" packages/sanity/src packages/@sanity/vision/src -g '!**/*.test.*' -g '!**/__test*__/**'
# every useMemo in those files, reduced to its first line and its dependency array
rg -nU --multiline-dotall -o "useMemo(<[^>]*>)?\(\s*\(\)\s*=>.{0,900}?\n\s*\[[^\]\n]*\],?\s*\)" $(rg -l "use(Sync)?Observable(Promise)?\(" packages/sanity/src -g '!**/*.test.*' -g '!**/__test*__/**') | rg ":\d+:\s*(useMemo|\[)"
# files that call useObservablePromise and use(); confirm the two calls sit in different components
rg -l "useObservablePromise\(" packages/sanity/src packages/@sanity/vision/src -g '!**/*.test.*' | xargs rg -n "useObservablePromise\(|\buse\("
Read each dependency array from the third command. Flag a call site when:
- A
useMemodependency that changes on edits: a document value, an array or object built during render, an inline[]or{}prop, or a recreated context value. of(...)or a.pipe(...)is built inline in render or per memo run instead of hoisted.- The dependency list is a superset of what the pipeline reads.
useObservableoruseSyncObservableis called without a stableinitialValue.use()reads a promise fromuseObservablePromisein the same component. See "react-rx:useObservablePromiseanduse()live in different components" inAGENTS.md.
Check these first (found with the commands above at this commit):
packages/sanity/src/core/hooks/useUserListWithPermissions.ts:state$listsdocumentValue, the live document fromCommentsProvider. Every edit rebuilds the grants observable.packages/sanity/src/core/form/studio/assetSourceMediaLibrary/hooks/useEnsureMediaLibrary.ts: the memo listsprops, andMediaLibraryProvider.tsxpasses them as an inline object literal.packages/sanity/src/core/canvas/actions/LinkToCanvas/useLinkToCanvas.ts: the memo listsdocument. An edit whileLinkToCanvasDialogis open reruns the preflight request.packages/sanity/src/core/releases/tool/components/releaseCTAButtons/ReleaseRevertButton/usePostPublishTransactions.ts: the memo listsdocuments, which updates live, so each update refetches the transaction log.
Count renders at runtime
Start the daemon and the studio per .agents/skills/react-devtools/SKILL.md and AGENTS.md. Then:
pnpm --filter sanity-test-studio exec agent-react-devtools profile start
# drive the interaction, for example type ten characters into a field
pnpm --filter sanity-test-studio exec agent-react-devtools profile stop
pnpm --filter sanity-test-studio exec agent-react-devtools profile rerenders --limit 10
pnpm --filter sanity-test-studio exec agent-react-devtools profile report @cN
pnpm --filter sanity-test-studio exec agent-react-devtools get component @cN # hook slots
Limits: it counts renders, not subscriptions, so a resubscribe that renders the same value is
invisible. Hidden <Activity> trees show as repeated first-mount fibers, not as re-renders.
Count subscriptions at runtime
- Add a temporary
console.log('[rx:build] <hook>')inside the observable factory (theuseMemo) and aconsole.log('[rx:subscribe] <hook>', <target id>)inside theswitchMapproject or the source factory. Remove both before you commit. - Drive the studio with Playwright in headed Chrome and count the lines by tag. Snapshot the
counters before and after the interaction. Run from the repo root with
node:
import {chromium} from 'playwright'
const counts = {}
const executablePath = '/usr/local/bin/google-chrome'
const browser = await chromium.launch({executablePath, headless: false})
const page = await browser.newPage()
page.on('console', (message) => {
const [tag] = message.text().split(' ', 1)
if (tag.startsWith('[rx:')) counts[tag] = (counts[tag] ?? 0) + 1
})
const token = encodeURIComponent(process.env.STUDIO_AUTH_TOKEN) // never log it
// an existing document in the /test workspace, for example one you created through the mutate API
await page.goto(`http://localhost:3333/test/structure/author;${process.env.DOC_ID}#token=${token}`)
const input = page.getByTestId('field-name').getByTestId('string-input')
await input.waitFor()
const before = {...counts}
await input.pressSequentially('ten chars!')
await page.waitForTimeout(3000)
console.log({before, after: counts})
await browser.close()
Pitfalls seen in this repo:
sanity devcan serve a stale revision after two edits of one file within seconds. Confirm anhmr updateline for your last edit in its terminal, or restart the server.- Keep the studio in bundledDev (the default) but run the server with the PID watchdog from the
AGENTS.mdgotchas. On vite 8.3 (PR #14700) one audit session pushed the server past 7 GB RSS.
Pass condition: during edits, [rx:build] is 0 for every host whose identity inputs did not
change, and [rx:subscribe] equals the number of distinct input changes per host.
Refactor
Reproduce the useValuePreview shape:
-
Name the identity inputs: the inputs whose change must render
initialValueagain. InuseValuePreviewthese areenabled,schemaTypeand the previewed document id. Everything else is a streamed input. -
Put the streamed inputs in one typed record (
PreviewInputs) anduseMemoit on its fields. Resolve overrides first, so the record carries the effective perspective and variant rather than both the caller's and the context's; a context change the caller overrides then never reaches the stream. One record, not one subject per input: two fields that change in the same render arrive together, soswitchMapnever subscribes an intermediate source. -
Hold the record in a
BehaviorSubjectfed from auseEffect. Replace the subject whenever any identity input changes,enabledincluded, seeded with the current render's inputs, with the "adjust state during render" pattern. A replacement observable must never read the inputs of an earlier render, and react-rx 6 subscribed it during render. This isuseInputsSubjectinuseValuePreview.ts:function useInputsSubject( enabled: boolean, schemaType: SchemaType | undefined, inputs: PreviewInputs, ): BehaviorSubject<PreviewInputs> { const documentKey = getPreviewDocumentKey(inputs.value) const [current, setCurrent] = useState(() => ({ enabled, schemaType, documentKey, inputs$: new BehaviorSubject(inputs), })) let {inputs$} = current if ( current.enabled !== enabled || current.schemaType !== schemaType || current.documentKey !== documentKey ) { inputs$ = new BehaviorSubject(inputs) setCurrent({enabled, schemaType, documentKey, inputs$}) } useEffect(() => { inputs$.next(inputs) }, [inputs$, inputs]) return inputs$ } -
Build the observable in a
useMemowhose dependencies are the identity inputs, the subject and the store function only. Pipeinputs$throughdistinctUntilChanged(dequal),switchMapinto the source, thendistinctUntilChangedwith an output comparator (isSameStateinuseValuePreview.ts) that compares the value withreact-fast-compareand errors by identity. -
Hoist constant observables to module scope, as in
IDLE_STATE_OBSERVABLE = of(IDLE_STATE), so returning one from the memo keeps a single identity and store. -
Keep
useSyncObservable(observable, INITIAL_STATE)when consumers read the first frame synchronously. UseuseObservableotherwise.
Cost the pattern accepts: a change that alters the output takes one extra render (render with the previous snapshot, the effect pushes, the store notifies, render again). A change that leaves the output equal costs no extra render.
Do not apply the pattern when the observable has no value-shaped inputs (ids, strings and stores
only) or when consumers need the render-time synchronous update on every change. Do not reach for
the deprecated useUnique to stabilize an input.
Test
Copy the harness pattern from useValuePreview.test.tsx and assert on literal frames and counts:
- A
Harnesscomponent pushes every rendered frame ({isLoading, title, error}) into an array. - The mocked source is an
Observablethat countssubscriptions.activeandsubscriptions.totalin its subscribe function and teardown. flush()awaits one macrotask insideact, so react-rx'sshare({resetOnRefCountZero: () => timer(0, asapScheduler)})releases the old source before you assert counts.
Write these three tests. They catch the regressions the refactor guards against:
- Same target, edited twice:
frames.slice(settled).filter((frame) => frame.isLoading)is[]and, afterflush(),subscriptionsis{active: 1, total: 3}. - Equal inputs rebuilt every render (a new
[]prop or an equal object):{active: 1, total: 1}. - Identity change (another document or schema type): every frame since the switch is the loading frame, the previous target's title never renders, then the new title renders.
At this commit useValuePreview.test.tsx (23 tests) passes on the installed react-rx 7.0.0, and
main's previous hook fails 7 of them there: loading frames on same-document edits and perspective
changes, a second render for an edit that leaves the preview unchanged, three previews for equal
inline inputs, a resubscribe on an overridden context change, and StrictMode. To see which of those
the react-rx 6 warm-up masked, run the file against the 6.0.1 dist. The installed dist files are hard
links into the pnpm store, so never write into them in place; unlink first:
RX=packages/sanity/node_modules/react-rx/dist
cp -a $RX /tmp/react-rx7-dist
(cd /tmp && npm pack react-rx@6.0.1 --silent && tar xzf react-rx-6.0.1.tgz)
rm $RX/index.js $RX/index.d.ts && cp /tmp/package/dist/index.js /tmp/package/dist/index.d.ts $RX/
pnpm vitest run --project=sanity <the test file>
rm $RX/index.js $RX/index.d.ts && cp /tmp/react-rx7-dist/index.js /tmp/react-rx7-dist/index.d.ts $RX/
Version History
- 584242a Current 2026-09-23 00:59


