Skip to content

fix(native): subscribe a component's style & rule effect once it commits - #603

Merged
danstepanov merged 8 commits into
nativewind:mainfrom
sammoore:fix/commit-subscribe-combined
Dec 2, 2026
Merged

danstepanov merged 8 commits into
nativewind:mainfrom
sammoore:fix/commit-subscribe-combined

Conversation

@sammoore

@sammoore sammoore commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

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, useNativeCss subscribed and unsubscribed both ruleEffect and styleEffect during render (updateRules() and getStyledProps()), which caused several concurrent-rendering bugs:

  1. Cross-component update during render: a sibling mutating a shared observable (e.g. vw) during render triggered "Cannot update a component while rendering a different component".
  2. Leaked subscriptions on discarded renders: a render abandoned behind a <Suspense> fallback left styleEffect subscribed 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.
  3. Detached subscriptions on suspended transitions: when a class change suspended and was discarded, updateRules() had already unsubscribed the committed element's styleEffect (a v5 regression from fix: resolve react-native-css styling and tooling regressions on Expo 57 #451) and replaced its ruleEffect subscriptions, leaving the committed element stale on subsequent viewport, media-query, or dark: changes.
  4. Stale cache after throwing computations: a computed observable whose computation threw could leave a partial/stale cached state on subsequent reads.

Fix

This PR combines #485 (commit-time styleEffect subscription + versioned/source-cached observables + stylesFamily replay re-insert) and #486 (commit-time ruleEffect subscription via recorded reads + committed-state rule re-evaluation) into one coherent change. See those PRs for the independent fixes.

Combining them lets a single useLayoutEffect manage both ruleEffect and styleEffect. Overall, the implementation is 10–28% faster and uses 10.2% less JS heap than main rather 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: Add family.getOrInsert and re-insert a stylesFamily entry when React replays effects after cleanup (StrictMode / <Activity>).
  • 5e7024a: Record ruleReads without subscribing during updateRules(), evaluate ruleEffect.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, lazy sources, and zero-alloc cleanupEffect:
    • Add a dual-package-safe global change counter (globalThis.__react_native_css_changes), store obs.version as a plain field, inline get(), and stamp checkedAt = changes.count inside compute() so an immediate second unobserved read skips re-walking sources.
    • Allocate the sources Map lazily only when a computed observable actually reads a source (zero Map allocation for static stylesObs).
    • Make cleanupEffect() zero-allocation (early-return when empty; iterate Set directly without Array.from), skip Array.from in batched notify(), and make family.getOrInsert single-lookup.
  • 9fa0795 — Unified commit effect & stale state/version fixes:
    • Replace the multiple effects and useRef(state) with a single useLayoutEffect([ruleReads, stylesObs]), storing committed on ruleEffect and restoring getStyledProps's original signature.
    • Refresh ruleEffect.committed on forceUpdate even when ruleReads observes the same observables, preventing ruleEffect.run() from re-evaluating against stale currentProps/guards.
    • Track styleEffect.lastObs / lastVersion in cleanup so re-showing an <Activity> after an earlier styleEffect.run() update does not spuriously re-render (while still catching up if values changed while hidden).
  • 3d9ace3 — Flat RenderReads, deferred style guards, and initial-mount guard skip:
    • Store RenderReads as a flat [observable0, version0, ...] array instead of N 2-tuple arrays, share EMPTY_READS for unstyled components, use direct recordRead() in rules.ts (avoiding per-call object/closure allocation on static classes), and compare in-order in readSameObservables() / avoid Set allocation in observeReads() when effect.observers.size === 0.
    • Defer reading stylesObs.get().guards to testGuards() (converted to an indexed for loop), keep state.inheritedVariables/inheritedContainers updated on all returns, and skip testGuards() on the initial mount render and identical post-updateRules retries.
  • d265f75 — Regression tests:
    • Cover forceUpdate + media query evaluating against latest committed props and <Activity> hide/show version replay after a viewport update in src/__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).

Scenario main (ec1c615) This PR (d265f75) Δ
remount 113.4 ms 96.1 ms -15.3%
remount, stable inline style 113.8 ms 98.1 ms -13.8%
rerender, same props 43.8 ms 43.6 ms -0.5%
rerender, new inline style 80.9 ms 79.0 ms -2.4%
remount, wrapped without classes 50.5 ms 46.4 ms -8.1%
remount, raw react-native (control) 11.7 ms 12.1 ms +3.9%
mount, shared className 42.7 ms 36.0 ms -15.7%
mount, unique className strings 50.1 ms 41.7 ms -16.7%
mount, unique rule sets, repeat 64.5 ms 52.2 ms -19.1%
mount, unique rule sets, first time 68.2 ms 54.2 ms -20.5%
rerender, className toggles 41.3 ms 39.9 ms -3.6%
mount, active: pseudo-class 48.6 ms 42.7 ms -12.1%
mount, media query 45.6 ms 36.2 ms -20.7%
mount, themed axis border colour 51.5 ms 42.5 ms -17.4%
theme change, :root prefers-color-scheme 50.4 ms 50.7 ms +0.7%
theme change, dark: utilities 129.3 ms 93.2 ms -27.9%
theme change, vars() provider 127.9 ms 108.6 ms -15.1%
theme change, VariableContextProvider 133.9 ms 109.3 ms -18.4%
memory, mounted tree (JS heap) 13.8 MiB 12.4 MiB -10.2%
memory, raw react-native (JS heap) (control) 3.5 MiB 3.5 MiB +0.0%

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).
  • ESLint across all modified source and test files — clean (0 errors).

YevheniiKotyrlo and others added 8 commits December 2, 2026 16:06
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
@sammoore
sammoore force-pushed the fix/commit-subscribe-combined branch from d265f75 to c917594 Compare December 2, 2026 21:51
@sammoore
sammoore marked this pull request as ready for review December 2, 2026 21:58
@danstepanov
danstepanov merged commit c24629e into nativewind:main Dec 2, 2026
5 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants