Repository navigation
fix(native): subscribe a component's style & rule effect once it commits - #603
Merged
danstepanov merged 8 commits intoDec 2, 2026
Merged
Conversation
A render subscribed the component's style effect to every observable it
read, and updateRules unsubscribed it from the previous styles, so a
render React discards (a suspended transition, a Suspense fallback) left
the effect on the observables of a component that never mounted. Every
later change to those styles ran that component's effect ("Can't perform
a React state update on a component that hasn't mounted yet"), and the
discarded render could detach a mounted component from the styles it
still shows.
A render now reads through a getter that subscribes nothing and records
each read beside the observable's version, and getStyledProps takes that
getter, so every read obeys the same gate. After every commit the style
effect observes exactly what that render read, releases what it no
longer reads, and re-renders when a read moved since the render.
Observables carry a version, and a computed value keeps the sources it
was computed from with their versions, so a read without a subscriber
is served from cache until a source changes, and a first subscriber
keeps the value instead of computing it again.
The sources a computation had read when it threw described no value, so a later read found them unchanged and returned the previous value without computing. A throwing computation now forgets its sources, and the next read computes again.
…effects StrictMode's effect replay and a re-shown <Activity> clean an element's effects up and run them again. The cleanup's unsubscribe drops the element's styles entry from the cache, and the commit then re-subscribes the entry the element still holds, so its hash maps to nothing. The next rule pass that keeps the element's rules finds no entry, builds another and renders; releasing the old entry then deletes the new one, which shares its hash, so every later such pass does the same. An entry that gains its first observer goes back under its hash when the hash holds nothing.
updateRules unsubscribed the rule effect from the previous rules and subscribed it to every rule and condition it read while a render ran, so a re-render React discards (a suspended transition) left a mounted element on the discarded render's rules and off the ones it still shows: a media query on the committed class stopped applying. The rule pass now reads through a recording getter, and the state it produces carries what it read. A layout effect makes the rule effect observe exactly that once the state commits, releases what it no longer reads, and runs the pass again when a read moved since. A pass that keeps the same rules keeps the state unless it read other observables. testRule takes the element's key beside the getter, since the getter no longer identifies the element. This replaces the mount effect's catch-up: a first commit, a StrictMode replay and a re-shown Activity all observe the reads the state carries, so the dependency snapshots cleanupEffect took, hasChangedDependencies and the committed flag go. The rule effect computes its update from the committed state and sets it as a value. An updater is computed eagerly from the state React last rendered, which a render it discards still writes, so after a discarded class change the update was computed from the discarded state and bailed out. A pass that changes nothing sets nothing, so a resize that moves no rule renders nothing. # Conflicts: # src/native/react/rules.ts # src/native/react/useNativeCss.ts # src/native/reactivity.ts
…nd zero-alloc cleanupEffect
…ix stale committed state
sammoore
force-pushed
the
fix/commit-subscribe-combined
branch
from
December 2, 2026 21:51
d265f75 to
c917594
Compare
sammoore
marked this pull request as ready for review
December 2, 2026 21:58
danstepanov
approved these changes
Dec 2, 2026
This was referenced Dec 2, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Supersedes #485 and #486 by combining both commit-time subscription fixes into a single PR with performance and memory improvements (preserving @YevheniiKotyrlo's original 4 commits).
Issue
React may discard a render (StrictMode, Suspense fallbacks, interrupted transitions) or replay an effect without re-rendering (
<Activity>, StrictMode). Previously,useNativeCsssubscribed and unsubscribed bothruleEffectandstyleEffectduring render (updateRules()andgetStyledProps()), which caused several concurrent-rendering bugs:vw) during render triggered"Cannot update a component while rendering a different component".<Suspense>fallback leftstyleEffectsubscribed for the lifetime of the app, causing"Can't perform a React state update on a component that hasn't mounted yet"on the next update.updateRules()had already unsubscribed the committed element'sstyleEffect(a v5 regression from fix: resolve react-native-css styling and tooling regressions on Expo 57 #451) and replaced itsruleEffectsubscriptions, leaving the committed element stale on subsequent viewport, media-query, ordark:changes.Fix
This PR combines #485 (commit-time
styleEffectsubscription + versioned/source-cached observables +stylesFamilyreplay re-insert) and #486 (commit-timeruleEffectsubscription via recorded reads + committed-state rule re-evaluation) into one coherent change. See those PRs for the independent fixes.Combining them lets a single
useLayoutEffectmanage bothruleEffectandstyleEffect. Overall, the implementation is 10–28% faster and uses 10.2% less JS heap thanmainrather than regressing render performance.Key Changes
Core Commit-Time Subscription (Original Commits by @YevheniiKotyrlo)
4abac72: Read styles without subscribing during render; version observables and cache computed sources so unobserved reads don't recompute on commit.c731a38: Reset source tracking if a computed observable throws so the next read recomputes cleanly.887bcc2: Addfamily.getOrInsertand re-insert astylesFamilyentry when React replays effects after cleanup (StrictMode /<Activity>).5e7024a: RecordruleReadswithout subscribing duringupdateRules(), evaluateruleEffect.run()from committed state (not a React state updater), and remove perf: avoid calculating styles/rules twice on first mount #466's snapshot catch-up mechanism.Performance Improvements & Correctness Fixes
863500d— Observable caching, lazysources, and zero-alloccleanupEffect:globalThis.__react_native_css_changes), storeobs.versionas a plain field, inlineget(), and stampcheckedAt = changes.countinsidecompute()so an immediate second unobserved read skips re-walking sources.sourcesMaplazily only when a computed observable actually reads a source (zeroMapallocation for staticstylesObs).cleanupEffect()zero-allocation (early-return when empty; iterateSetdirectly withoutArray.from), skipArray.fromin batchednotify(), and makefamily.getOrInsertsingle-lookup.9fa0795— Unified commit effect & stale state/version fixes:useRef(state)with a singleuseLayoutEffect([ruleReads, stylesObs]), storingcommittedonruleEffectand restoringgetStyledProps's original signature.ruleEffect.committedonforceUpdateeven whenruleReadsobserves the same observables, preventingruleEffect.run()from re-evaluating against stalecurrentProps/guards.styleEffect.lastObs/lastVersionin cleanup so re-showing an<Activity>after an earlierstyleEffect.run()update does not spuriously re-render (while still catching up if values changed while hidden).3d9ace3— FlatRenderReads, deferred style guards, and initial-mount guard skip:RenderReadsas a flat[observable0, version0, ...]array instead ofN2-tuple arrays, shareEMPTY_READSfor unstyled components, use directrecordRead()inrules.ts(avoiding per-call object/closure allocation on static classes), and compare in-order inreadSameObservables()/ avoidSetallocation inobserveReads()wheneffect.observers.size === 0.stylesObs.get().guardstotestGuards()(converted to an indexedforloop), keepstate.inheritedVariables/inheritedContainersupdated on all returns, and skiptestGuards()on the initial mount render and identical post-updateRulesretries.d265f75— Regression tests:forceUpdate+ media query evaluating against latest committed props and<Activity>hide/show version replay after a viewport update insrc/__tests__/native/reactivity-lifecycle.test.tsx.Benchmark Results
Local Hermes CLI (
HBC v98,BENCH_GC=1, 1,000 items / 2,003 views, 4 interleaved rounds pooled):ec1c615(main) →d265f75(fix/commit-subscribe-combined).main(ec1c615)d265f75)remountremount, stable inline stylererender, same propsrerender, new inline styleremount, wrapped without classesremount, raw react-native(control)mount, shared classNamemount, unique className stringsmount, unique rule sets, repeatmount, unique rule sets, first timererender, className togglesmount, active: pseudo-classmount, media querymount, themed axis border colourtheme change, :root prefers-color-schemetheme change, dark: utilitiestheme change, vars() providertheme change, VariableContextProvidermemory, mounted tree (JS heap)memory, raw react-native (JS heap)(control)Verification
yarn test src/— 113/113 suites, 2,326/2,326 tests passing (including StrictMode,<Activity>,<Suspense>, transition, and both new regression tests).npx tsc --noEmit -p tsconfig.build.json— clean (0 errors).