From ba87ff1456ab13a9b4828ee3d7239edb9fe34c53 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 16 Oct 2026 12:53:47 +0300 Subject: [PATCH 1/8] fix(native): subscribe the style effect to what a committed render read 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. --- .../native/reactivity-dependencies.test.tsx | 121 ++++++++++++++- .../native/reactivity-lifecycle.test.tsx | 136 ++++++++++++++++- src/native/react/rules.ts | 6 +- src/native/react/useNativeCss.ts | 25 ++- src/native/reactivity.ts | 144 +++++++++++++----- src/native/styles/index.ts | 4 +- 6 files changed, 388 insertions(+), 48 deletions(-) diff --git a/src/__tests__/native/reactivity-dependencies.test.tsx b/src/__tests__/native/reactivity-dependencies.test.tsx index f008cbd2..45f1e81e 100644 --- a/src/__tests__/native/reactivity-dependencies.test.tsx +++ b/src/__tests__/native/reactivity-dependencies.test.tsx @@ -2,8 +2,11 @@ import { cleanupEffect, family, observable, + observeReads, + recordReads, weakFamily, type Effect, + type Getter, } from "../../native/reactivity"; test.each([0, false, "", null, undefined, NaN])( @@ -58,7 +61,7 @@ test("computed dependencies follow a conditional branch even when its value is u const first = observable(10); const second = observable(10); const selected = observable(true); - const compute = jest.fn((get: import("../../native/reactivity").Getter) => + const compute = jest.fn((get: Getter) => get(selected) ? get(first) : get(second), ); const value = observable(compute); @@ -136,3 +139,119 @@ test("a family deletes a key by value only while the key still maps to it", () = expect(cached.deleteIf("shared", replacement)).toBe(true); expect(cached.size()).toBe(0); }); + +test("a computed value read without a subscriber is computed once until a source changes", () => { + const source = observable(10); + const compute = jest.fn((get: Getter) => ({ doubled: get(source) * 2 })); + const value = observable(compute); + const first = value.get(); + expect(value.get()).toBe(first); + expect(compute).toHaveBeenCalledTimes(1); + source.set(20); + expect(value.get()).toEqual({ doubled: 40 }); + expect(compute).toHaveBeenCalledTimes(2); +}); + +test("a read without a subscriber subscribes nothing", () => { + const source = observable(10); + const value = observable((get) => get(source) * 2); + value.get(); + expect(source.observers.size).toBe(0); + expect(value.observers.size).toBe(0); +}); + +test("a first subscriber keeps the value an unsubscribed read computed", () => { + const source = observable(10); + const compute = jest.fn((get: Getter) => ({ doubled: get(source) * 2 })); + const value = observable(compute); + const read = value.get(); + const run = jest.fn(); + const subscriber: Effect = { observers: new Set(), run }; + expect(value.get(subscriber)).toBe(read); + expect(compute).toHaveBeenCalledTimes(1); + source.set(20); + expect(run).toHaveBeenCalledTimes(1); + expect(value.get(subscriber)).toEqual({ doubled: 40 }); + cleanupEffect(subscriber); +}); + +test("a chain of computed values read without subscribers follows a change at its root", () => { + const root = observable(1); + const middle = observable((get) => get(root) + 1); + const leaf = observable((get) => get(middle) * 10); + expect(leaf.get()).toBe(20); + root.set(4); + expect(leaf.get()).toBe(50); + expect(root.observers.size).toBe(0); +}); + +test("a value released by its last subscriber is not computed again until a source changes", () => { + const source = observable(10); + const compute = jest.fn((get: Getter) => get(source) * 2); + const value = observable(compute); + const subscriber: Effect = { observers: new Set(), run: jest.fn() }; + value.get(subscriber); + cleanupEffect(subscriber); + expect(value.get()).toBe(20); + expect(compute).toHaveBeenCalledTimes(1); + source.set(30); + expect(value.get()).toBe(60); + expect(compute).toHaveBeenCalledTimes(2); +}); + +test("an observable's version moves only when its value changes", () => { + const source = observable(1); + const parity = observable((get) => get(source) % 2); + const sourceVersion = source.version; + parity.get(); + const parityVersion = parity.version; + source.set(1); + expect(source.version).toBe(sourceVersion); + source.set(3); + expect(source.version).not.toBe(sourceVersion); + parity.get(); + expect(parity.version).toBe(parityVersion); + source.set(4); + parity.get(); + expect(parity.version).not.toBe(parityVersion); +}); + +test("recorded reads subscribe nothing until a commit observes them", () => { + const source = observable(10); + const value = observable((get) => get(source) * 2); + const recorded = recordReads(); + expect(recorded.read(value)).toBe(20); + expect(value.observers.size).toBe(0); + const subscriber: Effect = { observers: new Set(), run: jest.fn() }; + expect(observeReads(subscriber, recorded.reads)).toBe("unmoved"); + expect(value.observers.has(subscriber)).toBe(true); + cleanupEffect(subscriber); +}); + +test("observing recorded reads answers moved for a change since the read", () => { + const source = observable(10); + const value = observable((get) => get(source) * 2); + const recorded = recordReads(); + recorded.read(value); + source.set(30); + const run = jest.fn(); + const subscriber: Effect = { observers: new Set(), run }; + expect(observeReads(subscriber, recorded.reads)).toBe("moved"); + expect(run).not.toHaveBeenCalled(); + cleanupEffect(subscriber); +}); + +test("observing recorded reads releases what the effect observed and the commit no longer read", () => { + const first = observable(1); + const second = observable(2); + const subscriber: Effect = { observers: new Set(), run: jest.fn() }; + const before = recordReads(); + before.read(first); + observeReads(subscriber, before.reads); + const after = recordReads(); + after.read(second); + observeReads(subscriber, after.reads); + expect(first.observers.size).toBe(0); + expect(second.observers.has(subscriber)).toBe(true); + cleanupEffect(subscriber); +}); diff --git a/src/__tests__/native/reactivity-lifecycle.test.tsx b/src/__tests__/native/reactivity-lifecycle.test.tsx index 4e3047f7..45ef6db5 100644 --- a/src/__tests__/native/reactivity-lifecycle.test.tsx +++ b/src/__tests__/native/reactivity-lifecycle.test.tsx @@ -1,7 +1,7 @@ -import { StrictMode } from "react"; +import { startTransition, StrictMode, Suspense, use } from "react"; import { Text } from "react-native"; -import { act, render } from "@testing-library/react-native"; +import { act, render, renderAsync } from "@testing-library/react-native"; import { View } from "react-native-css/components/View"; import { registerCSS } from "react-native-css/jest"; import { useNativeVariable } from "react-native-css/native"; @@ -11,6 +11,7 @@ import { } from "react-native-css/native-internal"; import { cleanupEffect, observable, vw } from "../../native/reactivity"; +import * as calculatePropsModule from "../../native/styles/calculate-props"; test("cleaned observers receive no later notifications", () => { const value = observable(0); @@ -156,6 +157,137 @@ test("StrictMode viewport consumers remain reactive and release subscriptions", }); }); +function captureConsoleErrors() { + const error = jest.spyOn(console, "error").mockImplementation(jest.fn()); + return { + messages: () => error.mock.calls.map(([message]) => String(message)), + restore: () => { + error.mockRestore(); + }, + }; +} + +const neverResolves = new Promise(jest.fn()); + +test("a viewport change between render and commit reaches the element once it commits", () => { + registerCSS(".audit-render-window { width: 10vw; }"); + const original = vw.get(); + const errors = captureConsoleErrors(); + function ResizeDuringRender() { + vw.set(800); + return null; + } + try { + const screen = render( + <> + + + , + ); + expect(errors.messages()).toEqual([]); + expect(screen.getByTestId("sample").props.style.width).toBe(80); + screen.unmount(); + } finally { + errors.restore(); + act(() => { + vw.set(original); + }); + } +}); + +function NeverResolves() { + return use(neverResolves); +} + +test("a render React discards leaves no subscription and takes no later update", async () => { + registerCSS(".audit-discarded-render { width: 10vw; }"); + const original = vw.get(); + const before = vw.observers.size; + const errors = captureConsoleErrors(); + try { + const screen = await renderAsync( + loading}> + + + , + ); + expect(screen.getByTestId("fallback")).toBeTruthy(); + expect(screen.queryByTestId("sample")).toBeNull(); + expect(vw.observers.size).toBe(before); + await act(() => { + vw.set(900); + return Promise.resolve(); + }); + expect(errors.messages()).toEqual([]); + await screen.unmountAsync(); + } finally { + errors.restore(); + act(() => { + vw.set(original); + }); + } +}); + +test("mounting an element computes its styles once", () => { + registerCSS(".audit-single-computation { width: 10vw; }"); + const computations = jest.spyOn(calculatePropsModule, "calculateProps"); + try { + const screen = render( + , + ); + expect(screen.getByTestId("sample").props.style.width).toBeGreaterThan(0); + expect(computations).toHaveBeenCalledTimes(1); + screen.unmount(); + } finally { + computations.mockRestore(); + } +}); + +test("a render React discards leaves the committed element subscribed", async () => { + registerCSS( + ".audit-kept-first { width: 10vw; } .audit-kept-second { width: 20px; }", + ); + const original = vw.get(); + function Sample({ + className, + suspended, + }: { + className: string; + suspended: boolean; + }) { + return ( + <> + + + {suspended ? : null} + + + ); + } + const screen = render( + , + ); + try { + await act(() => { + startTransition(() => { + screen.rerender(); + }); + return Promise.resolve(); + }); + expect(screen.getByTestId("sample").props.style.width).toBe(original / 10); + await act(() => { + vw.set(1000); + return Promise.resolve(); + }); + expect(screen.getByTestId("sample").props.style.width).toBe(100); + } finally { + screen.unmount(); + act(() => { + vw.set(original); + }); + } +}); + test("class changes detach the old rule subscription", () => { registerCSS( ".audit-rule-first { width: 10px; } .audit-rule-second { width: 20px; }", diff --git a/src/native/react/rules.ts b/src/native/react/rules.ts index 6f469b3f..cbcb94ab 100644 --- a/src/native/react/rules.ts +++ b/src/native/react/rules.ts @@ -256,8 +256,7 @@ export function updateRules( // Generate a StyleObservable for this unique set of rules / variables const stylesObs = stylesFamily(generateStateHash(state, rules), rules); - // Get the guards without subscribing to the observable - // We will subscribe within the render using the StyleEffect + // Get the guards without subscribing to the observable; the style effect subscribes when the component commits guards.push(...stylesObs.get().guards); // If these are the same styles with no inline variables, we can skip the update @@ -269,9 +268,6 @@ export function updateRules( return state; } - // Remove this component from the old observer - state.stylesObs?.unsubscribe(state.styleEffect); - return { ...state, currentProps, diff --git a/src/native/react/useNativeCss.ts b/src/native/react/useNativeCss.ts index 8b513f14..d44b042e 100644 --- a/src/native/react/useNativeCss.ts +++ b/src/native/react/useNativeCss.ts @@ -4,6 +4,7 @@ import { Fragment, useContext, useEffect, + useLayoutEffect, useRef, useState, type ComponentType, @@ -19,6 +20,8 @@ import { ContainerContext, hasChangedDependencies, weakFamily, + observeReads, + recordReads, type ContainerContextValue, type Effect, type Getter, @@ -119,16 +122,30 @@ export function useNativeCss( // Distinguishes a fresh mount from an effect replay (Activity, StrictMode) const hasCommittedRef = useRef(false); + // React may discard a render, so a render subscribes nothing and its commit subscribes what it read + const styleReads = recordReads(); + + useLayoutEffect(() => { + if (observeReads(state.styleEffect, styleReads.reads) === "moved") { + state.styleEffect.run(); + } + }); + + useLayoutEffect( + () => () => { + cleanupEffect(state.styleEffect); + }, + [state.styleEffect], + ); + useEffect(() => { // Reconnect subscriptions after React replays an effect setup. if (state.ruleEffect.observers.size === 0) { if (hasCommittedRef.current || hasChangedDependencies(state.ruleEffect)) { // Replay, or conditions changed since the initializer: recalculate. state.ruleEffect.run(); - state.styleEffect.run(); } else { // Fresh mount: resubscribe to the initializer's dependencies. - // styleEffect resubscribes itself during render. for (const observable of state.ruleEffect.dependencies ?? []) { observable.get(state.ruleEffect); } @@ -137,9 +154,8 @@ export function useNativeCss( hasCommittedRef.current = true; return () => { cleanupEffect(state.ruleEffect); - cleanupEffect(state.styleEffect); }; - }, [state.ruleEffect, state.styleEffect]); + }, [state.ruleEffect]); // Check if our derived state has changed (e.g the className prop) if ( @@ -165,6 +181,7 @@ export function useNativeCss( let props = getStyledProps( state, + styleReads.read, originalProps, type === Image ? adaptImageProps : undefined, ); diff --git a/src/native/reactivity.ts b/src/native/reactivity.ts index 06170a1a..51b60214 100644 --- a/src/native/reactivity.ts +++ b/src/native/reactivity.ts @@ -23,6 +23,8 @@ export type Effect = { export type Observable = { observers: Set; + /** Advances each time the value changes, so a read can be checked later without subscribing */ + readonly version: number; get: (effect?: Effect) => Value; set: (arg: Arg) => void; run: () => void; @@ -39,46 +41,80 @@ export function observable( init: Value | Read, equality: (value1: Value, value2: Value) => boolean = Object.is, ) { - let value: Value; - let isStatic = typeof init !== "function"; - let didInit: boolean | undefined; + const isStatic = typeof init !== "function"; + let value = (isStatic ? init : undefined) as Value; + let version = 0; let lastArg: Arg | undefined; - - if (typeof init !== "function") { - value = init; - didInit = true; - } + /** What a computed value was last computed from, each source beside its version then */ + let sources: Map, number> | undefined; const observers = new Set(); const effect: Effect = { observers: new Set(), run: () => { - if (!isStatic) { - cleanupEffect(effect); - const nextValue = (init as Read)(getter, lastArg); - if (equality(value, nextValue)) { - return; - } - value = nextValue; + if (isStatic || compute(lastArg)) { + notify(); } - - notify(); }, }; - const getter: Getter = (observable) => - observable.get(observers.size > 0 ? effect : undefined); + const getter: Getter = (source) => { + const sourceValue = source.get(observers.size > 0 ? effect : undefined); + sources?.set(source, source.version); + return sourceValue; + }; + + /** Computes the value, answering whether it changed. Subscribes to the sources only while observed. */ + function compute(arg: Arg | undefined) { + cleanupEffect(effect); + const isFirstComputation = sources === undefined; + sources = new Map(); + const nextValue = (init as Read)(getter, arg); + if (!isFirstComputation && equality(value, nextValue)) { + return false; + } + value = nextValue; + version++; + return true; + } + + /** The sources of a value that is still current, bringing each computed source up to date first */ + function currentSources() { + if (sources === undefined) { + return undefined; + } + for (const [source, seenVersion] of sources) { + source.get(); + if (source.version !== seenVersion) { + return undefined; + } + } + return sources; + } + + function subscribe(subscriber: Effect) { + observers.add(subscriber); + subscriber.observers.add(obs); + } function get(subscriber?: Effect) { - if (subscriber) { - if (observers.size === 0 && !isStatic) didInit = false; - observers.add(subscriber); - subscriber.observers.add(obs); + if (isStatic) { + if (subscriber) subscribe(subscriber); + return value; } - if (!didInit) { - cleanupEffect(effect); - value = (init as Read)(getter, lastArg); - didInit = observers.size > 0; + + // While observed, a computed value is kept current by its sources + const isObserved = observers.size > 0; + if (subscriber) subscribe(subscriber); + if (!isObserved) { + const current = currentSources(); + if (current === undefined) { + compute(lastArg); + } else if (observers.size > 0) { + for (const source of current.keys()) { + source.get(effect); + } + } } return value; @@ -90,17 +126,12 @@ export function observable( return; } value = arg as unknown as Value; + version++; } else { - cleanupEffect(effect); - const nextValue = (init as Read)(getter, arg); - - didInit = observers.size > 0; lastArg = arg; - - if (equality(value, nextValue)) { + if (!compute(arg)) { return; } - value = nextValue; } notify(); @@ -120,13 +151,15 @@ export function observable( const obs: Observable = { observers, + get version() { + return version; + }, get, set, run: effect.run, unsubscribe(subscriber) { if (observers.delete(subscriber) && observers.size === 0 && !isStatic) { cleanupEffect(effect); - didInit = false; } subscriber.observers.delete(obs); }, @@ -173,6 +206,47 @@ export function batch(update: () => void) { observableBatch.current = undefined; } +/** What a render read, each observable beside its version when read */ +export type RenderReads = readonly (readonly [ + observable: Observable, + version: number, +])[]; + +/** A getter that subscribes nothing and records each read, for a render React may still discard */ +export function recordReads(): { read: Getter; reads: RenderReads } { + const reads: (readonly [Observable, number])[] = []; + return { + read: (observable) => { + const value = observable.get(); + reads.push([observable, observable.version]); + return value; + }, + reads, + }; +} + +/** Make `effect` observe exactly what a committed render read, answering whether any of it moved since */ +export function observeReads( + effect: Effect, + reads: RenderReads, +): "moved" | "unmoved" { + const read = new Set>(); + let moved = false; + for (const [observable, version] of reads) { + read.add(observable); + observable.get(effect); + if (observable.version !== version) { + moved = true; + } + } + for (const observable of Array.from(effect.observers)) { + if (!read.has(observable)) { + observable.unsubscribe(effect); + } + } + return moved ? "moved" : "unmoved"; +} + /** Family Helpers ************************************************************/ export function family( diff --git a/src/native/styles/index.ts b/src/native/styles/index.ts index 9757c127..7ff2a446 100644 --- a/src/native/styles/index.ts +++ b/src/native/styles/index.ts @@ -13,6 +13,7 @@ import { observable, VAR_SYMBOL, type Effect, + type Getter, type VariableContextValue, } from "../reactivity"; import { calculateProps } from "./calculate-props"; @@ -161,6 +162,7 @@ export const stylesFamily = family( export function getStyledProps( state: ComponentState, + read: Getter, inline: Record | undefined | null, adaptProps: ( props: Record | undefined, @@ -168,7 +170,7 @@ export function getStyledProps( ) { let result: Record | undefined; - const styledProps = state.stylesObs?.get(state.styleEffect); + const styledProps = state.stylesObs ? read(state.stylesObs) : undefined; // Each config merges a complete props object. Preserve its full target path // before the next config merges unrelated inline props over that object. From d3d5860fdc23c7dc36a0d9bdba29428918873a7a Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 16 Oct 2026 01:46:12 +0300 Subject: [PATCH 2/8] fix(native): compute a value again after its computation throws 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. --- .../native/reactivity-dependencies.test.tsx | 15 +++++++++++++++ src/native/reactivity.ts | 9 ++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/__tests__/native/reactivity-dependencies.test.tsx b/src/__tests__/native/reactivity-dependencies.test.tsx index 45f1e81e..62dbf441 100644 --- a/src/__tests__/native/reactivity-dependencies.test.tsx +++ b/src/__tests__/native/reactivity-dependencies.test.tsx @@ -152,6 +152,21 @@ test("a computed value read without a subscriber is computed once until a source expect(compute).toHaveBeenCalledTimes(2); }); +test("a computed value whose computation threw computes again on its next read", () => { + const source = observable(0); + const value = observable((get) => { + const current = get(source); + if (current === 0) { + throw new Error("no value yet"); + } + return current * 2; + }); + expect(() => value.get()).toThrow("no value yet"); + expect(() => value.get()).toThrow("no value yet"); + source.set(5); + expect(value.get()).toBe(10); +}); + test("a read without a subscriber subscribes nothing", () => { const source = observable(10); const value = observable((get) => get(source) * 2); diff --git a/src/native/reactivity.ts b/src/native/reactivity.ts index 51b60214..da31f7c6 100644 --- a/src/native/reactivity.ts +++ b/src/native/reactivity.ts @@ -69,7 +69,14 @@ export function observable( cleanupEffect(effect); const isFirstComputation = sources === undefined; sources = new Map(); - const nextValue = (init as Read)(getter, arg); + let nextValue: Value; + try { + nextValue = (init as Read)(getter, arg); + } catch (error) { + // A computation that threw produced no value, so the next read computes again rather than trusting a partial read + sources = undefined; + throw error; + } if (!isFirstComputation && equality(value, nextValue)) { return false; } From ac6d853d7e7fbd6e83ca7e16bac8221fe5b557d7 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 16 Oct 2026 10:35:09 +0300 Subject: [PATCH 3/8] fix(native): put a styles entry back when React re-runs an element's effects StrictMode's effect replay and a re-shown 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. --- .../native/reactivity-lifecycle.test.tsx | 69 ++++++++++++++++++- src/native/reactivity.ts | 6 ++ src/native/styles/index.ts | 11 ++- 3 files changed, 83 insertions(+), 3 deletions(-) diff --git a/src/__tests__/native/reactivity-lifecycle.test.tsx b/src/__tests__/native/reactivity-lifecycle.test.tsx index 45ef6db5..0d47fd8e 100644 --- a/src/__tests__/native/reactivity-lifecycle.test.tsx +++ b/src/__tests__/native/reactivity-lifecycle.test.tsx @@ -1,4 +1,11 @@ -import { startTransition, StrictMode, Suspense, use } from "react"; +import { + Activity, + startTransition, + StrictMode, + Suspense, + use, + type ReactElement, +} from "react"; import { Text } from "react-native"; import { act, render, renderAsync } from "@testing-library/react-native"; @@ -10,7 +17,8 @@ import { StyleCollection, } from "react-native-css/native-internal"; -import { cleanupEffect, observable, vw } from "../../native/reactivity"; +import * as useNativeCssModule from "../../native/react/useNativeCss"; +import { cleanupEffect, observable, vh, vw } from "../../native/reactivity"; import * as calculatePropsModule from "../../native/styles/calculate-props"; test("cleaned observers receive no later notifications", () => { @@ -302,3 +310,60 @@ test("class changes detach the old rule subscription", () => { screen.unmount(); expect(second.observers.size).toBe(0); }); + +function setViewport(width: number, height: number) { + act(() => { + vw.set(width); + vh.set(height); + }); +} + +const ELEMENT_MOUNTS = [ + ["mounted once", (element: ReactElement) => render(element)], + [ + "whose effects StrictMode ran twice", + (element: ReactElement) => render({element}), + ], + [ + "that Activity hid and showed again", + (element: ReactElement) => { + const screen = render({element}); + screen.rerender({element}); + screen.rerender({element}); + return screen; + }, + ], +] as const; + +test.each(ELEMENT_MOUNTS)( + "a viewport change that moves no rule renders nothing and computes no styles on an element %s", + (_shape, mount) => { + registerCSS(` + .audit-rule-unmoved { height: 5px; } + @media (min-width: 600px) { .audit-rule-unmoved { width: 10px; } } + `); + const originalWidth = vw.get(); + const originalHeight = vh.get(); + setViewport(500, 500); + const screen = mount( + , + ); + const renders = jest.spyOn(useNativeCssModule, "useNativeCss"); + const computations = jest.spyOn(calculatePropsModule, "calculateProps"); + try { + act(() => { + vw.set(550); + }); + expect(renders).not.toHaveBeenCalled(); + expect(computations).not.toHaveBeenCalled(); + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + height: 5, + }); + } finally { + computations.mockRestore(); + renders.mockRestore(); + screen.unmount(); + setViewport(originalWidth, originalHeight); + } + }, +); diff --git a/src/native/reactivity.ts b/src/native/reactivity.ts index da31f7c6..6f5fbabf 100644 --- a/src/native/reactivity.ts +++ b/src/native/reactivity.ts @@ -277,6 +277,12 @@ export function family( size() { return map.size; }, + getOrInsert(key: Key, value: Result) { + if (!map.has(key)) { + map.set(key, value); + } + return map.get(key) as Result; + }, clear() { return map.clear(); }, diff --git a/src/native/styles/index.ts b/src/native/styles/index.ts index 7ff2a446..1046151a 100644 --- a/src/native/styles/index.ts +++ b/src/native/styles/index.ts @@ -147,8 +147,17 @@ export const stylesFamily = family( const obs = observable((read) => calculateProps(read, sortedRules)); - const unsubscribe = obs.unsubscribe; + const { get, unsubscribe } = obs; return Object.assign(obs, { + get: (effect?: Effect) => { + const wasUnobserved = obs.observers.size === 0; + const value = get(effect); + // React runs an element's effects again after cleaning them up (StrictMode, a re-shown ), so the entry it holds comes back + if (effect && wasUnobserved) { + stylesFamily.getOrInsert(hash, obs); + } + return value; + }, unsubscribe: (effect: Effect) => { unsubscribe(effect); if (obs.observers.size === 0) { From 4b4fb11a78b8a7d514bbacbe2e1883fa3eafa09e Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 16 Oct 2026 12:57:59 +0300 Subject: [PATCH 4/8] fix(native): subscribe a component's rule effect once it commits 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 --- src/__tests__/native/config-identity.test.ts | 1 + .../native/reactivity-lifecycle.test.tsx | 262 ++++++++++++++++-- src/__tests__/types/exact-optional.test.ts | 2 - src/native/conditions/index.ts | 11 +- src/native/react/rules.ts | 32 ++- src/native/react/useNativeCss.ts | 59 ++-- src/native/reactivity.ts | 36 ++- 7 files changed, 305 insertions(+), 98 deletions(-) diff --git a/src/__tests__/native/config-identity.test.ts b/src/__tests__/native/config-identity.test.ts index 5edbaf66..25c4b10d 100644 --- a/src/__tests__/native/config-identity.test.ts +++ b/src/__tests__/native/config-identity.test.ts @@ -25,6 +25,7 @@ const stateFor = (configs: Config[]): ComponentState => { inheritedVariables, ruleEffect, ruleEffectGetter: (observable) => observable.get(ruleEffect), + ruleReads: [], styleEffect: { observers: new Set(), run: () => undefined }, }; }; diff --git a/src/__tests__/native/reactivity-lifecycle.test.tsx b/src/__tests__/native/reactivity-lifecycle.test.tsx index 0d47fd8e..f88bf137 100644 --- a/src/__tests__/native/reactivity-lifecycle.test.tsx +++ b/src/__tests__/native/reactivity-lifecycle.test.tsx @@ -17,6 +17,7 @@ import { StyleCollection, } from "react-native-css/native-internal"; +import * as rulesModule from "../../native/react/rules"; import * as useNativeCssModule from "../../native/react/useNativeCss"; import { cleanupEffect, observable, vh, vw } from "../../native/reactivity"; import * as calculatePropsModule from "../../native/styles/calculate-props"; @@ -207,6 +208,41 @@ function NeverResolves() { return use(neverResolves); } +function SampleBesideSuspense({ + className, + suspended, +}: { + className: string; + suspended: boolean; +}) { + return ( + <> + + + {suspended ? : null} + + + ); +} + +async function renderDiscardedClassChange( + committedClassName: string, + discardedClassName: string, +) { + const screen = render( + , + ); + await act(() => { + startTransition(() => { + screen.rerender( + , + ); + }); + return Promise.resolve(); + }); + return screen; +} + test("a render React discards leaves no subscription and takes no later update", async () => { registerCSS(".audit-discarded-render { width: 10vw; }"); const original = vw.get(); @@ -256,32 +292,11 @@ test("a render React discards leaves the committed element subscribed", async () ".audit-kept-first { width: 10vw; } .audit-kept-second { width: 20px; }", ); const original = vw.get(); - function Sample({ - className, - suspended, - }: { - className: string; - suspended: boolean; - }) { - return ( - <> - - - {suspended ? : null} - - - ); - } - const screen = render( - , + const screen = await renderDiscardedClassChange( + "audit-kept-first", + "audit-kept-second", ); try { - await act(() => { - startTransition(() => { - screen.rerender(); - }); - return Promise.resolve(); - }); expect(screen.getByTestId("sample").props.style.width).toBe(original / 10); await act(() => { vw.set(1000); @@ -318,6 +333,76 @@ function setViewport(width: number, height: number) { }); } +test("a class change React discards leaves the committed element following its rules", async () => { + registerCSS(` + .audit-rule-kept-first { height: 5px; } + @media (min-width: 600px) { .audit-rule-kept-first { width: 10px; } } + .audit-rule-kept-second { width: 20px; } + `); + const originalWidth = vw.get(); + const originalHeight = vh.get(); + setViewport(500, 500); + const screen = await renderDiscardedClassChange( + "audit-rule-kept-first", + "audit-rule-kept-second", + ); + try { + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + height: 5, + }); + await act(() => { + vw.set(700); + return Promise.resolve(); + }); + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + height: 5, + width: 10, + }); + } finally { + screen.unmount(); + setViewport(originalWidth, originalHeight); + } +}); + +test("a class change React discards leaves no subscription to the discarded rules", async () => { + registerCSS(` + .audit-rule-gone-first { width: 10px; } + @media (min-width: 600px) { .audit-rule-gone-second { width: 20px; } } + `); + const discardedRules = StyleCollection.styles("audit-rule-gone-second"); + const viewportObservers = vw.observers.size; + const screen = await renderDiscardedClassChange( + "audit-rule-gone-first", + "audit-rule-gone-second", + ); + try { + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + width: 10, + }); + expect(discardedRules.observers.size).toBe(0); + expect(vw.observers.size).toBe(viewportObservers); + } finally { + screen.unmount(); + } +}); + +test("mounting an element runs its rule pass once", () => { + registerCSS(".audit-single-rule-pass { width: 10px; }"); + const rulePasses = jest.spyOn(rulesModule, "updateRules"); + try { + const screen = render( + , + ); + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + width: 10, + }); + expect(rulePasses).toHaveBeenCalledTimes(1); + screen.unmount(); + } finally { + rulePasses.mockRestore(); + } +}); + const ELEMENT_MOUNTS = [ ["mounted once", (element: ReactElement) => render(element)], [ @@ -367,3 +452,132 @@ test.each(ELEMENT_MOUNTS)( } }, ); + +test("a viewport change between render and commit reaches the element's rules once it commits", () => { + registerCSS(` + .audit-rule-window { height: 5px; } + @media (min-width: 600px) { .audit-rule-window { width: 10px; } } + `); + const originalWidth = vw.get(); + const originalHeight = vh.get(); + setViewport(500, 500); + const errors = captureConsoleErrors(); + function ResizeDuringRender() { + vw.set(700); + return null; + } + try { + const screen = render( + <> + + + , + ); + expect(errors.messages()).toEqual([]); + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + height: 5, + width: 10, + }); + screen.unmount(); + } finally { + errors.restore(); + setViewport(originalWidth, originalHeight); + } +}); + +test("a rule pass that reads more after a change follows what it read", () => { + registerCSS(` + .audit-rule-reads-more { height: 5px; } + @media (min-width: 600px) and (min-height: 600px) { + .audit-rule-reads-more { width: 10px; } + } + `); + const originalWidth = vw.get(); + const originalHeight = vh.get(); + setViewport(500, 500); + const screen = render( + , + ); + try { + act(() => { + vw.set(700); + }); + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + height: 5, + }); + act(() => { + vh.set(700); + }); + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + height: 5, + width: 10, + }); + } finally { + screen.unmount(); + setViewport(originalWidth, originalHeight); + } +}); + +test("StrictMode rule consumers remain reactive and release subscriptions", () => { + registerCSS(` + .audit-strict-rule { height: 5px; } + @media (min-width: 600px) { .audit-strict-rule { width: 10px; } } + `); + const rules = StyleCollection.styles("audit-strict-rule"); + const originalWidth = vw.get(); + const originalHeight = vh.get(); + setViewport(500, 500); + const viewportObservers = vw.observers.size; + const screen = render( + + + , + ); + try { + act(() => { + vw.set(700); + }); + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + height: 5, + width: 10, + }); + } finally { + screen.unmount(); + expect(rules.observers.size).toBe(0); + expect(vw.observers.size).toBe(viewportObservers); + setViewport(originalWidth, originalHeight); + } +}); + +test("an element Activity hid follows rules that changed while it was hidden", async () => { + registerCSS(` + .audit-activity-rule { height: 5px; } + @media (min-width: 600px) { .audit-activity-rule { width: 10px; } } + `); + const originalWidth = vw.get(); + const originalHeight = vh.get(); + setViewport(500, 500); + function Sample({ mode }: { mode: "visible" | "hidden" }) { + return ( + + + + ); + } + const screen = await renderAsync(); + try { + await screen.rerenderAsync(); + await act(() => { + vw.set(700); + return Promise.resolve(); + }); + await screen.rerenderAsync(); + expect(screen.getByTestId("sample").props.style).toStrictEqual({ + height: 5, + width: 10, + }); + } finally { + await screen.unmountAsync(); + setViewport(originalWidth, originalHeight); + } +}); diff --git a/src/__tests__/types/exact-optional.test.ts b/src/__tests__/types/exact-optional.test.ts index 46fd9391..e0708da5 100644 --- a/src/__tests__/types/exact-optional.test.ts +++ b/src/__tests__/types/exact-optional.test.ts @@ -95,8 +95,6 @@ export const config: Config = { source: "a", target: "a", nativeStyleMapping: un export const effect: Effect = { observers: new Set(), run() {}, - dependencies: undefined, - snapshots: undefined, }; `; diff --git a/src/native/conditions/index.ts b/src/native/conditions/index.ts index 8886f689..1ad028f9 100644 --- a/src/native/conditions/index.ts +++ b/src/native/conditions/index.ts @@ -15,12 +15,13 @@ import { testMediaQuery } from "./media-query"; export function testRule( rule: StyleRule, + key: WeakKey, get: Getter, props: Props, guards: RenderGuard[], containerContext: ContainerContextValue, ) { - if (rule.p && !pseudoClasses(rule.p, get)) { + if (rule.p && !pseudoClasses(rule.p, key, get)) { return false; } if (rule.m && !testMediaQuery(rule.m, get)) { @@ -39,16 +40,16 @@ export function testRule( return true; } -function pseudoClasses(query: PseudoClassesQuery, get: Getter) { +function pseudoClasses(query: PseudoClassesQuery, key: WeakKey, get: Getter) { // IMPORTANT: active needs: to be first. Modifies a global value // that we use to determine if the component should be a pressable - if (query.a && !get(activeFamily(get))) { + if (query.a && !get(activeFamily(key))) { return false; } - if (query.h && !get(hoverFamily(get))) { + if (query.h && !get(hoverFamily(key))) { return false; } - if (query.f && !get(focusFamily(get))) { + if (query.f && !get(focusFamily(key))) { return false; } return true; diff --git a/src/native/react/rules.ts b/src/native/react/rules.ts index cbcb94ab..a343ea57 100644 --- a/src/native/react/rules.ts +++ b/src/native/react/rules.ts @@ -8,13 +8,15 @@ import type { RenderGuard } from "../conditions/guards"; import { getDeepPath } from "../objects"; import { activeFamily, - cleanupEffect, containerLayoutFamily, focusFamily, hoverFamily, + readSameObservables, + recordReads, VAR_SYMBOL, weakFamily, type ContainerContextValue, + type Getter, type VariableContextValue, } from "../reactivity"; import { stylesFamily } from "../styles"; @@ -32,7 +34,8 @@ export function updateRules( forceUpdate = false, isRerender = true, ): ComponentState { - cleanupEffect(state.ruleEffect); + // React may discard the render this pass runs in, so it subscribes nothing and the commit observes what it read + const ruleReads = recordReads(); const guards: RenderGuard[] = []; const rules = new Set(); if (forceUpdate) { @@ -66,9 +69,7 @@ export function updateRules( if (typeof source === "string") { const classNames = source.split(/\s+/); for (const className of classNames) { - styleRuleSet.push( - ...StyleCollection.styles(className).get(state.ruleEffect), - ); + styleRuleSet.push(...ruleReads.read(StyleCollection.styles(className))); } } @@ -87,7 +88,7 @@ export function updateRules( INLINE_RULE_SYMBOL in item && typeof item[INLINE_RULE_SYMBOL] === "string" ) { - pushInlineRule(state, item, styleRuleSet); + pushInlineRule(ruleReads.read, item, styleRuleSet); } } } else if ( @@ -101,7 +102,7 @@ export function updateRules( INLINE_RULE_SYMBOL in target && typeof target[INLINE_RULE_SYMBOL] === "string" ) { - pushInlineRule(state, target, styleRuleSet); + pushInlineRule(ruleReads.read, target, styleRuleSet); } } @@ -125,6 +126,7 @@ export function updateRules( !testRule( rule, state.ruleEffectGetter, + ruleReads.read, currentProps, guards, inheritedContainers, @@ -222,6 +224,7 @@ export function updateRules( pressable, variables, containers, + ruleReads: ruleReads.reads, }; } @@ -244,7 +247,7 @@ export function updateRules( ruleVariableNames, inlineVariables, state.variables, - state.ruleEffectGetter, + ruleReads.read, ); } @@ -265,7 +268,9 @@ export function updateRules( !inlineVariables.size && !publishedChanged ) { - return state; + return readSameObservables(state.ruleReads, ruleReads.reads) + ? state + : { ...state, ruleReads: ruleReads.reads }; } return { @@ -277,6 +282,7 @@ export function updateRules( guards, animated, pressable, + ruleReads: ruleReads.reads, }; } @@ -290,13 +296,9 @@ const getRuleVariation = weakFamily((rule: StyleRule) => { }); }); -function pushInlineRule( - state: ComponentState, - item: any, - styleRuleSet: StyleRule[], -) { +function pushInlineRule(read: Getter, item: any, styleRuleSet: StyleRule[]) { for (const className of item[INLINE_RULE_SYMBOL].split(/\s+/)) { - let inlineRuleSet = StyleCollection.styles(className).get(state.ruleEffect); + let inlineRuleSet = read(StyleCollection.styles(className)); for (let rule of inlineRuleSet) { styleRuleSet.push(rule); diff --git a/src/native/react/useNativeCss.ts b/src/native/react/useNativeCss.ts index d44b042e..77c9f599 100644 --- a/src/native/react/useNativeCss.ts +++ b/src/native/react/useNativeCss.ts @@ -3,7 +3,6 @@ import { createElement, Fragment, useContext, - useEffect, useLayoutEffect, useRef, useState, @@ -18,13 +17,13 @@ import { testGuards, type RenderGuard } from "../conditions/guards"; import { cleanupEffect, ContainerContext, - hasChangedDependencies, - weakFamily, observeReads, recordReads, + weakFamily, type ContainerContextValue, type Effect, type Getter, + type RenderReads, type VariableContextValue, } from "../reactivity"; import { animatedComponentFamily } from "../reanimated"; @@ -44,6 +43,8 @@ export type ComponentState = { /** Reactive tracking */ ruleEffect: Effect; ruleEffectGetter: Getter; + /** What the rule pass that produced this state read, for the commit to observe */ + ruleReads: RenderReads; styleEffect: Effect; /** The components props */ @@ -83,7 +84,14 @@ export function useNativeCss( */ const ruleEffect: Effect = { observers: new Set(), - run: () => setState((state) => updateRules(state)), + run: () => { + // Not an updater: React computes one eagerly from its last rendered state, which a render it discards still writes + const committed = committedState.current; + const next = updateRules(committed); + if (next !== committed) { + setState(next); + } + }, }; /** @@ -97,10 +105,11 @@ export function useNativeCss( run: () => setState((state) => ({ ...state })), }; - const initialState = updateRules( + return updateRules( { ruleEffect, ruleEffectGetter: (observable) => observable.get(ruleEffect), + ruleReads: [], styleEffect, configs, inheritedContainers, @@ -113,18 +122,22 @@ export function useNativeCss( false, false, ); - // State initializers may be discarded by React StrictMode. Subscribe once - // the component commits instead of retaining an abandoned initializer. - cleanupEffect(ruleEffect); - return initialState; }); - - // Distinguishes a fresh mount from an effect replay (Activity, StrictMode) - const hasCommittedRef = useRef(false); + const committedState = useRef(state); // React may discard a render, so a render subscribes nothing and its commit subscribes what it read const styleReads = recordReads(); + useLayoutEffect(() => { + committedState.current = state; + }); + + useLayoutEffect(() => { + if (observeReads(state.ruleEffect, state.ruleReads) === "moved") { + state.ruleEffect.run(); + } + }, [state.ruleEffect, state.ruleReads]); + useLayoutEffect(() => { if (observeReads(state.styleEffect, styleReads.reads) === "moved") { state.styleEffect.run(); @@ -133,30 +146,12 @@ export function useNativeCss( useLayoutEffect( () => () => { + cleanupEffect(state.ruleEffect); cleanupEffect(state.styleEffect); }, - [state.styleEffect], + [state.ruleEffect, state.styleEffect], ); - useEffect(() => { - // Reconnect subscriptions after React replays an effect setup. - if (state.ruleEffect.observers.size === 0) { - if (hasCommittedRef.current || hasChangedDependencies(state.ruleEffect)) { - // Replay, or conditions changed since the initializer: recalculate. - state.ruleEffect.run(); - } else { - // Fresh mount: resubscribe to the initializer's dependencies. - for (const observable of state.ruleEffect.dependencies ?? []) { - observable.get(state.ruleEffect); - } - } - } - hasCommittedRef.current = true; - return () => { - cleanupEffect(state.ruleEffect); - }; - }, [state.ruleEffect]); - // Check if our derived state has changed (e.g the className prop) if ( testGuards(state, originalProps, inheritedVariables, inheritedContainers) diff --git a/src/native/reactivity.ts b/src/native/reactivity.ts index 6f5fbabf..141e615c 100644 --- a/src/native/reactivity.ts +++ b/src/native/reactivity.ts @@ -15,10 +15,6 @@ import type { ReducedMotionPreference } from "../runtime.types"; export type Effect = { observers: Set>; run(): void; - /** Dependencies recorded by the last cleanupEffect() */ - dependencies?: Observable[] | undefined; - /** Dependency values recorded by the last cleanupEffect() */ - snapshots?: [Observable, unknown][] | undefined; }; export type Observable = { @@ -177,28 +173,13 @@ export function observable( export function cleanupEffect(effect: Effect) { if (!effect) return; - const dependencies = (effect.dependencies = Array.from(effect.observers)); - // Snapshot before detaching so computed observables return cached values - effect.snapshots = dependencies.map( - (observable) => - [observable, observable.get()] as [Observable, unknown], - ); + const dependencies = Array.from(effect.observers); effect.observers.clear(); for (const dep of dependencies) { dep.unsubscribe(effect); } } -/** Whether any of the effect's dependencies changed since cleanupEffect() */ -export function hasChangedDependencies(effect: Effect): boolean { - const snapshots = effect.snapshots; - if (!snapshots) return false; - for (const [observable, value] of snapshots) { - if (!Object.is(observable.get(), value)) return true; - } - return false; -} - export function batch(update: () => void) { const notified = new Set(); observableBatch.current = notified; @@ -232,6 +213,21 @@ export function recordReads(): { read: Getter; reads: RenderReads } { }; } +/** Whether two passes read the same observables, whatever their versions */ +export function readSameObservables(left: RenderReads, right: RenderReads) { + const leftObservables = new Set(left.map(([observable]) => observable)); + const rightObservables = new Set(right.map(([observable]) => observable)); + if (leftObservables.size !== rightObservables.size) { + return false; + } + for (const observable of leftObservables) { + if (!rightObservables.has(observable)) { + return false; + } + } + return true; +} + /** Make `effect` observe exactly what a committed render read, answering whether any of it moved since */ export function observeReads( effect: Effect, From 8055d13d9a257da13024cfbe151cc4888c2af7cf Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Wed, 2 Dec 2026 14:53:02 -0500 Subject: [PATCH 5/8] perf(native): optimize observable source caching, lazy sources map, and zero-alloc cleanupEffect --- src/native/reactivity.ts | 123 +++++++++++++++++++++------------------ 1 file changed, 67 insertions(+), 56 deletions(-) diff --git a/src/native/reactivity.ts b/src/native/reactivity.ts index 141e615c..98d1a09d 100644 --- a/src/native/reactivity.ts +++ b/src/native/reactivity.ts @@ -33,16 +33,25 @@ export type ObservableBatch = { current?: Set; }; +declare global { + var __react_native_css_changes: { count: number } | undefined; +} + +/** Advances whenever any observable's value changes, so an unobserved value checked since then skips re-walking its sources. Pinned like the reactivity state for dual-package splits. */ +const changes = (globalThis.__react_native_css_changes ??= { count: 0 }); + export function observable( init: Value | Read, equality: (value1: Value, value2: Value) => boolean = Object.is, ) { const isStatic = typeof init !== "function"; let value = (isStatic ? init : undefined) as Value; - let version = 0; let lastArg: Arg | undefined; - /** What a computed value was last computed from, each source beside its version then */ + let hasComputed = false; + /** Lazily allocated only when a computed observable reads at least one source */ let sources: Map, number> | undefined; + /** The value of `changes.count` when `sources` were last confirmed current */ + let checkedAt = -1; const observers = new Set(); const effect: Effect = { @@ -56,68 +65,67 @@ export function observable( const getter: Getter = (source) => { const sourceValue = source.get(observers.size > 0 ? effect : undefined); - sources?.set(source, source.version); + (sources ??= new Map()).set(source, source.version); return sourceValue; }; /** Computes the value, answering whether it changed. Subscribes to the sources only while observed. */ function compute(arg: Arg | undefined) { cleanupEffect(effect); - const isFirstComputation = sources === undefined; - sources = new Map(); + const isFirstComputation = !hasComputed; + sources = undefined; let nextValue: Value; try { nextValue = (init as Read)(getter, arg); } catch (error) { // A computation that threw produced no value, so the next read computes again rather than trusting a partial read + hasComputed = false; sources = undefined; + checkedAt = -1; throw error; } + hasComputed = true; if (!isFirstComputation && equality(value, nextValue)) { + checkedAt = changes.count; return false; } value = nextValue; - version++; + obs.version++; + changes.count++; + checkedAt = changes.count; return true; } - /** The sources of a value that is still current, bringing each computed source up to date first */ - function currentSources() { - if (sources === undefined) { - return undefined; - } - for (const [source, seenVersion] of sources) { - source.get(); - if (source.version !== seenVersion) { - return undefined; - } - } - return sources; - } - - function subscribe(subscriber: Effect) { - observers.add(subscriber); - subscriber.observers.add(obs); - } - function get(subscriber?: Effect) { - if (isStatic) { - if (subscriber) subscribe(subscriber); + // While observed, a computed value is kept current by its sources + const isObserved = observers.size > 0; + if (subscriber) { + observers.add(subscriber); + subscriber.observers.add(obs); + } + if (isStatic || isObserved) { return value; } - // While observed, a computed value is kept current by its sources - const isObserved = observers.size > 0; - if (subscriber) subscribe(subscriber); - if (!isObserved) { - const current = currentSources(); - if (current === undefined) { - compute(lastArg); - } else if (observers.size > 0) { - for (const source of current.keys()) { - source.get(effect); + let current = hasComputed; + if (current && sources !== undefined && checkedAt !== changes.count) { + // Bring each source up to date first, and compute again if any moved + for (const [source, seenVersion] of sources) { + source.get(); + if (source.version !== seenVersion) { + current = false; + break; } } + if (current) checkedAt = changes.count; + } + + if (!current) { + compute(lastArg); + } else if (subscriber && sources !== undefined) { + for (const source of sources.keys()) { + source.get(effect); + } } return value; @@ -129,7 +137,8 @@ export function observable( return; } value = arg as unknown as Value; - version++; + obs.version++; + changes.count++; } else { lastArg = arg; if (!compute(arg)) { @@ -143,20 +152,23 @@ export function observable( } function notify() { - Array.from(observers).forEach((observer) => { - if (observableBatch.current) { - observableBatch.current.add(observer); - } else { - observer.run(); + if (observers.size === 0) return; + if (observableBatch.current) { + const batchSet = observableBatch.current; + for (const observer of observers) { + batchSet.add(observer); } - }); + return; + } + const snapshot = Array.from(observers); + for (let i = 0; i < snapshot.length; i++) { + snapshot[i]!.run(); + } } - const obs: Observable = { + const obs: Observable & { version: number } = { observers, - get version() { - return version; - }, + version: 0, get, set, run: effect.run, @@ -172,12 +184,11 @@ export function observable( } export function cleanupEffect(effect: Effect) { - if (!effect) return; - const dependencies = Array.from(effect.observers); - effect.observers.clear(); - for (const dep of dependencies) { + if (!effect || effect.observers.size === 0) return; + for (const dep of effect.observers) { dep.unsubscribe(effect); } + effect.observers.clear(); } export function batch(update: () => void) { @@ -274,10 +285,10 @@ export function family( return map.size; }, getOrInsert(key: Key, value: Result) { - if (!map.has(key)) { - map.set(key, value); - } - return map.get(key) as Result; + const existing = map.get(key); + if (existing !== undefined || map.has(key)) return existing!; + map.set(key, value); + return value; }, clear() { return map.clear(); From b7d6b8066b32a95052522046d704d61ca4581373 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Wed, 2 Dec 2026 14:54:20 -0500 Subject: [PATCH 6/8] perf(native): unify commit subscriptions into one layout effect and fix stale committed state --- src/native/react/rules.ts | 6 ++-- src/native/react/useNativeCss.ts | 56 +++++++++++++++----------------- src/native/styles/index.ts | 5 ++- 3 files changed, 33 insertions(+), 34 deletions(-) diff --git a/src/native/react/rules.ts b/src/native/react/rules.ts index a343ea57..6f488166 100644 --- a/src/native/react/rules.ts +++ b/src/native/react/rules.ts @@ -262,13 +262,15 @@ export function updateRules( // Get the guards without subscribing to the observable; the style effect subscribes when the component commits guards.push(...stylesObs.get().guards); - // If these are the same styles with no inline variables, we can skip the update + // If these are the same styles with no inline variables, we can skip the update. + // When forceUpdate created a new state (changed currentProps/guards), return a + // fresh ruleReads so the commit effect refreshes ruleEffect.committed. if ( state.stylesObs === stylesObs && !inlineVariables.size && !publishedChanged ) { - return readSameObservables(state.ruleReads, ruleReads.reads) + return !forceUpdate && readSameObservables(state.ruleReads, ruleReads.reads) ? state : { ...state, ruleReads: ruleReads.reads }; } diff --git a/src/native/react/useNativeCss.ts b/src/native/react/useNativeCss.ts index 77c9f599..94df093d 100644 --- a/src/native/react/useNativeCss.ts +++ b/src/native/react/useNativeCss.ts @@ -4,7 +4,6 @@ import { Fragment, useContext, useLayoutEffect, - useRef, useState, type ComponentType, } from "react"; @@ -18,7 +17,6 @@ import { cleanupEffect, ContainerContext, observeReads, - recordReads, weakFamily, type ContainerContextValue, type Effect, @@ -64,6 +62,8 @@ export type ComponentState = { pressable?: undefined | boolean; }; +type RuleEffect = Effect & { committed: ComponentState }; + /** * useNativeCss is the native implementation of the useCssElement hook. */ @@ -82,11 +82,12 @@ export function useNativeCss( * * Use this when a rule condition changes, e.g FastRefresh or media queries */ - const ruleEffect: Effect = { + const ruleEffect: RuleEffect = { observers: new Set(), + committed: undefined!, run: () => { // Not an updater: React computes one eagerly from its last rendered state, which a render it discards still writes - const committed = committedState.current; + const committed = ruleEffect.committed; const next = updateRules(committed); if (next !== committed) { setState(next); @@ -105,7 +106,7 @@ export function useNativeCss( run: () => setState((state) => ({ ...state })), }; - return updateRules( + const initialState = updateRules( { ruleEffect, ruleEffectGetter: (observable) => observable.get(ruleEffect), @@ -122,35 +123,32 @@ export function useNativeCss( false, false, ); + ruleEffect.committed = initialState; + return initialState; }); - const committedState = useRef(state); - - // React may discard a render, so a render subscribes nothing and its commit subscribes what it read - const styleReads = recordReads(); - useLayoutEffect(() => { - committedState.current = state; - }); + // React may discard a render, so a render subscribes nothing and one layout effect + // subscribes both ruleEffect and styleEffect when a render commits. + let readVersion: number | undefined; + const { ruleEffect, ruleReads, styleEffect, stylesObs } = state; useLayoutEffect(() => { - if (observeReads(state.ruleEffect, state.ruleReads) === "moved") { - state.ruleEffect.run(); + (ruleEffect as RuleEffect).committed = state; + if (observeReads(ruleEffect, ruleReads) === "moved") { + ruleEffect.run(); } - }, [state.ruleEffect, state.ruleReads]); - - useLayoutEffect(() => { - if (observeReads(state.styleEffect, styleReads.reads) === "moved") { - state.styleEffect.run(); + if (stylesObs) { + // React replays the latest render's effect (StrictMode, a re-shown ), so readVersion is what it showed + stylesObs.get(styleEffect); + if (stylesObs.version !== readVersion) { + styleEffect.run(); + } } - }); - - useLayoutEffect( - () => () => { - cleanupEffect(state.ruleEffect); - cleanupEffect(state.styleEffect); - }, - [state.ruleEffect, state.styleEffect], - ); + return () => { + cleanupEffect(ruleEffect); + stylesObs?.unsubscribe(styleEffect); + }; + }, [ruleReads, stylesObs]); // Check if our derived state has changed (e.g the className prop) if ( @@ -176,10 +174,10 @@ export function useNativeCss( let props = getStyledProps( state, - styleReads.read, originalProps, type === Image ? adaptImageProps : undefined, ); + readVersion = stylesObs?.version; if (type === View && props?.onPress) { type = Pressable; diff --git a/src/native/styles/index.ts b/src/native/styles/index.ts index 1046151a..ce551f98 100644 --- a/src/native/styles/index.ts +++ b/src/native/styles/index.ts @@ -13,7 +13,6 @@ import { observable, VAR_SYMBOL, type Effect, - type Getter, type VariableContextValue, } from "../reactivity"; import { calculateProps } from "./calculate-props"; @@ -171,7 +170,6 @@ export const stylesFamily = family( export function getStyledProps( state: ComponentState, - read: Getter, inline: Record | undefined | null, adaptProps: ( props: Record | undefined, @@ -179,7 +177,8 @@ export function getStyledProps( ) { let result: Record | undefined; - const styledProps = state.stylesObs ? read(state.stylesObs) : undefined; + // Unsubscribed: the component subscribes once the render commits + const styledProps = state.stylesObs?.get(); // Each config merges a complete props object. Preserve its full target path // before the next config merges unrelated inline props over that object. From fac0e578d4e408923b70214d9f60df6b31aed14c Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Wed, 2 Dec 2026 14:55:41 -0500 Subject: [PATCH 7/8] perf(native): flatten ruleReads, defer style guards, and skip initial testGuards --- .../native/reactivity-dependencies.test.tsx | 26 ++++---- src/native/conditions/guards.ts | 58 ++++++++++++---- src/native/react/rules.ts | 62 +++++++++++------ src/native/react/useNativeCss.ts | 16 ++++- src/native/reactivity.ts | 66 +++++++++++-------- 5 files changed, 156 insertions(+), 72 deletions(-) diff --git a/src/__tests__/native/reactivity-dependencies.test.tsx b/src/__tests__/native/reactivity-dependencies.test.tsx index 62dbf441..58f2c1cf 100644 --- a/src/__tests__/native/reactivity-dependencies.test.tsx +++ b/src/__tests__/native/reactivity-dependencies.test.tsx @@ -3,7 +3,7 @@ import { family, observable, observeReads, - recordReads, + recordRead, weakFamily, type Effect, type Getter, @@ -234,11 +234,11 @@ test("an observable's version moves only when its value changes", () => { test("recorded reads subscribe nothing until a commit observes them", () => { const source = observable(10); const value = observable((get) => get(source) * 2); - const recorded = recordReads(); - expect(recorded.read(value)).toBe(20); + const reads: unknown[] = []; + expect(recordRead(reads, value)).toBe(20); expect(value.observers.size).toBe(0); const subscriber: Effect = { observers: new Set(), run: jest.fn() }; - expect(observeReads(subscriber, recorded.reads)).toBe("unmoved"); + expect(observeReads(subscriber, reads)).toBe("unmoved"); expect(value.observers.has(subscriber)).toBe(true); cleanupEffect(subscriber); }); @@ -246,12 +246,12 @@ test("recorded reads subscribe nothing until a commit observes them", () => { test("observing recorded reads answers moved for a change since the read", () => { const source = observable(10); const value = observable((get) => get(source) * 2); - const recorded = recordReads(); - recorded.read(value); + const reads: unknown[] = []; + recordRead(reads, value); source.set(30); const run = jest.fn(); const subscriber: Effect = { observers: new Set(), run }; - expect(observeReads(subscriber, recorded.reads)).toBe("moved"); + expect(observeReads(subscriber, reads)).toBe("moved"); expect(run).not.toHaveBeenCalled(); cleanupEffect(subscriber); }); @@ -260,12 +260,12 @@ test("observing recorded reads releases what the effect observed and the commit const first = observable(1); const second = observable(2); const subscriber: Effect = { observers: new Set(), run: jest.fn() }; - const before = recordReads(); - before.read(first); - observeReads(subscriber, before.reads); - const after = recordReads(); - after.read(second); - observeReads(subscriber, after.reads); + const before: unknown[] = []; + recordRead(before, first); + observeReads(subscriber, before); + const after: unknown[] = []; + recordRead(after, second); + observeReads(subscriber, after); expect(first.observers.size).toBe(0); expect(second.observers.has(subscriber)).toBe(true); cleanupEffect(subscriber); diff --git a/src/native/conditions/guards.ts b/src/native/conditions/guards.ts index 4edd6007..0aab6dbd 100644 --- a/src/native/conditions/guards.ts +++ b/src/native/conditions/guards.ts @@ -15,42 +15,74 @@ export type RenderGuard = | ["n", string, StyleDescriptor] | ["c", string, WeakKey]; -export function testGuards( - state: ComponentState, +function testGuardList( + guards: RenderGuard[] | undefined, currentProps: any, inheritedVariables: VariableContextValue, inheritedContainers: ContainerContextValue, -) { - return state.guards?.some((guard) => { - let result = false; +): boolean { + if (!guards) return false; + for (let i = 0; i < guards.length; i++) { + const guard = guards[i]!; switch (guard[0]) { case "a": // Attribute - result = currentProps?.[guard[1]] !== guard[2]; + if (currentProps?.[guard[1]] !== guard[2]) return true; break; case "d": // DataSet - result = currentProps?.dataSet?.[guard[1]] !== guard[2]; + if (currentProps?.dataSet?.[guard[1]] !== guard[2]) return true; break; case "v": // Variables - result = inheritedVariables[guard[1]] !== guard[2]; + if (inheritedVariables[guard[1]] !== guard[2]) return true; break; case "n": // A non-inheriting variable's value counts only once a later registration lets it inherit - result = + if ( registeredInheritance(guard[1]).get() && - inheritedVariables[guard[1]] !== guard[2]; + inheritedVariables[guard[1]] !== guard[2] + ) { + return true; + } break; case "c": // Containers - result = inheritedContainers[guard[1]] !== guard[2]; + if (inheritedContainers[guard[1]] !== guard[2]) return true; break; default: guard satisfies never; } + } + return false; +} + +export function testGuards( + state: ComponentState, + currentProps: any, + inheritedVariables: VariableContextValue, + inheritedContainers: ContainerContextValue, +) { + if ( + testGuardList( + state.guards, + currentProps, + inheritedVariables, + inheritedContainers, + ) + ) { + return true; + } + + if (state.stylesObs) { + return testGuardList( + state.stylesObs.get().guards, + currentProps, + inheritedVariables, + inheritedContainers, + ); + } - return result; - }); + return false; } diff --git a/src/native/react/rules.ts b/src/native/react/rules.ts index 6f488166..251a6b7a 100644 --- a/src/native/react/rules.ts +++ b/src/native/react/rules.ts @@ -9,14 +9,16 @@ import { getDeepPath } from "../objects"; import { activeFamily, containerLayoutFamily, + EMPTY_READS, focusFamily, hoverFamily, readSameObservables, - recordReads, + recordRead, VAR_SYMBOL, weakFamily, type ContainerContextValue, type Getter, + type RenderReads, type VariableContextValue, } from "../reactivity"; import { stylesFamily } from "../styles"; @@ -34,12 +36,23 @@ export function updateRules( forceUpdate = false, isRerender = true, ): ComponentState { - // React may discard the render this pass runs in, so it subscribes nothing and the commit observes what it read - const ruleReads = recordReads(); + // React may discard the render this pass runs in, so it subscribes nothing and the commit observes what it read. + // Allocate reads lazily so unstyled views share EMPTY_READS, and only create a Getter closure if needed. + let ruleReadsArr: unknown[] | undefined; + let readGetter: Getter | undefined; + const getRead: () => Getter = () => + (readGetter ??= (obs) => recordRead((ruleReadsArr ??= []), obs)); + const guards: RenderGuard[] = []; const rules = new Set(); if (forceUpdate) { - state = { ...state, guards, currentProps }; + state = { + ...state, + guards, + currentProps, + inheritedVariables, + inheritedContainers, + }; } let usesVariables = false; @@ -66,10 +79,15 @@ export function updateRules( const styleRuleSet = []; - if (typeof source === "string") { + if (typeof source === "string" && source.length > 0) { const classNames = source.split(/\s+/); - for (const className of classNames) { - styleRuleSet.push(...ruleReads.read(StyleCollection.styles(className))); + ruleReadsArr ??= []; + for (let i = 0; i < classNames.length; i++) { + const className = classNames[i]!; + if (className.length === 0) continue; + styleRuleSet.push( + ...recordRead(ruleReadsArr, StyleCollection.styles(className)), + ); } } @@ -88,7 +106,7 @@ export function updateRules( INLINE_RULE_SYMBOL in item && typeof item[INLINE_RULE_SYMBOL] === "string" ) { - pushInlineRule(ruleReads.read, item, styleRuleSet); + pushInlineRule(getRead(), item, styleRuleSet); } } } else if ( @@ -102,7 +120,7 @@ export function updateRules( INLINE_RULE_SYMBOL in target && typeof target[INLINE_RULE_SYMBOL] === "string" ) { - pushInlineRule(ruleReads.read, target, styleRuleSet); + pushInlineRule(getRead(), target, styleRuleSet); } } @@ -123,10 +141,11 @@ export function updateRules( } if ( + (rule.p || rule.m || rule.aq || rule.cq) && !testRule( rule, state.ruleEffectGetter, - ruleReads.read, + getRead(), currentProps, guards, inheritedContainers, @@ -215,16 +234,20 @@ export function updateRules( pressable = activeFamily.has(state.ruleEffectGetter); + const ruleReads: RenderReads = ruleReadsArr ?? EMPTY_READS; + if (!rules.size && !state.stylesObs && !inlineVariables.size) { return { ...state, currentProps, + inheritedVariables, + inheritedContainers, guards, animated, pressable, variables, containers, - ruleReads: ruleReads.reads, + ruleReads, }; } @@ -247,7 +270,7 @@ export function updateRules( ruleVariableNames, inlineVariables, state.variables, - ruleReads.read, + getRead(), ); } @@ -256,12 +279,11 @@ export function updateRules( } } - // Generate a StyleObservable for this unique set of rules / variables + // Generate a StyleObservable for this unique set of rules / variables. + // Style guards are read lazily by testGuards() on subsequent renders, avoiding + // an extra stylesObs.get() and array copy during updateRules(). const stylesObs = stylesFamily(generateStateHash(state, rules), rules); - // Get the guards without subscribing to the observable; the style effect subscribes when the component commits - guards.push(...stylesObs.get().guards); - // If these are the same styles with no inline variables, we can skip the update. // When forceUpdate created a new state (changed currentProps/guards), return a // fresh ruleReads so the commit effect refreshes ruleEffect.committed. @@ -270,21 +292,23 @@ export function updateRules( !inlineVariables.size && !publishedChanged ) { - return !forceUpdate && readSameObservables(state.ruleReads, ruleReads.reads) + return !forceUpdate && readSameObservables(state.ruleReads, ruleReads) ? state - : { ...state, ruleReads: ruleReads.reads }; + : { ...state, ruleReads }; } return { ...state, currentProps, + inheritedVariables, + inheritedContainers, stylesObs, variables, containers, guards, animated, pressable, - ruleReads: ruleReads.reads, + ruleReads, }; } diff --git a/src/native/react/useNativeCss.ts b/src/native/react/useNativeCss.ts index 94df093d..73390e54 100644 --- a/src/native/react/useNativeCss.ts +++ b/src/native/react/useNativeCss.ts @@ -75,7 +75,9 @@ export function useNativeCss( const inheritedVariables = useContext(VariableContext); const inheritedContainers = useContext(ContainerContext); + let isInitialRender = false; const [state, setState] = useState((): ComponentState => { + isInitialRender = true; /** * When fired, this effect will force the rules to be re-evaluated. * This will cause a re-render if there are different rules @@ -150,8 +152,20 @@ export function useNativeCss( }; }, [ruleReads, stylesObs]); - // Check if our derived state has changed (e.g the className prop) + // Check if our derived state has changed (e.g the className prop). + // Skip on the initial mount render and on the immediate retry render after + // updateRules() when props and contexts are identical to what updateRules + // just evaluated. + const canSkipGuards = + isInitialRender || + (state.stylesObs !== undefined && + state.stylesObs.observers.size === 0 && + originalProps === state.currentProps && + inheritedVariables === state.inheritedVariables && + inheritedContainers === state.inheritedContainers); + if ( + !canSkipGuards && testGuards(state, originalProps, inheritedVariables, inheritedContainers) ) { /** diff --git a/src/native/reactivity.ts b/src/native/reactivity.ts index 98d1a09d..c4016bed 100644 --- a/src/native/reactivity.ts +++ b/src/native/reactivity.ts @@ -205,29 +205,38 @@ export function batch(update: () => void) { observableBatch.current = undefined; } -/** What a render read, each observable beside its version when read */ -export type RenderReads = readonly (readonly [ - observable: Observable, - version: number, -])[]; - -/** A getter that subscribes nothing and records each read, for a render React may still discard */ -export function recordReads(): { read: Getter; reads: RenderReads } { - const reads: (readonly [Observable, number])[] = []; - return { - read: (observable) => { - const value = observable.get(); - reads.push([observable, observable.version]); - return value; - }, - reads, - }; +/** What a render read, stored flat as [observable0, version0, observable1, version1, ...] */ +export type RenderReads = readonly unknown[]; + +export const EMPTY_READS: RenderReads = []; + +/** Read an observable unsubscribed and append [observable, version] into a flat reads array */ +export function recordRead( + reads: unknown[], + observable: Observable, +): Value { + const value = observable.get(); + reads.push(observable, observable.version); + return value; } /** Whether two passes read the same observables, whatever their versions */ export function readSameObservables(left: RenderReads, right: RenderReads) { - const leftObservables = new Set(left.map(([observable]) => observable)); - const rightObservables = new Set(right.map(([observable]) => observable)); + if (left === right) return true; + // A pass over the same rules reads them in the same order, so compare in place before building sets + if (left.length === right.length) { + let i = 0; + while (i < left.length && left[i] === right[i]) i += 2; + if (i === left.length) return true; + } + const leftObservables = new Set(); + for (let i = 0; i < left.length; i += 2) { + leftObservables.add(left[i]); + } + const rightObservables = new Set(); + for (let i = 0; i < right.length; i += 2) { + rightObservables.add(right[i]); + } if (leftObservables.size !== rightObservables.size) { return false; } @@ -244,18 +253,23 @@ export function observeReads( effect: Effect, reads: RenderReads, ): "moved" | "unmoved" { - const read = new Set>(); + // An effect that observes nothing yet has nothing to release + const read = + effect.observers.size > 0 ? new Set>() : undefined; let moved = false; - for (const [observable, version] of reads) { - read.add(observable); + for (let i = 0; i < reads.length; i += 2) { + const observable = reads[i] as Observable; + read?.add(observable); observable.get(effect); - if (observable.version !== version) { + if (observable.version !== reads[i + 1]) { moved = true; } } - for (const observable of Array.from(effect.observers)) { - if (!read.has(observable)) { - observable.unsubscribe(effect); + if (read) { + for (const observable of effect.observers) { + if (!read.has(observable)) { + observable.unsubscribe(effect); + } } } return moved ? "moved" : "unmoved"; From c917594d1eb952a2157c01d77df0553b450716e6 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Wed, 2 Dec 2026 14:57:37 -0500 Subject: [PATCH 8/8] test(native): cover committed props on forceUpdate and Activity replay --- .../native/reactivity-lifecycle.test.tsx | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/src/__tests__/native/reactivity-lifecycle.test.tsx b/src/__tests__/native/reactivity-lifecycle.test.tsx index f88bf137..d9c22f78 100644 --- a/src/__tests__/native/reactivity-lifecycle.test.tsx +++ b/src/__tests__/native/reactivity-lifecycle.test.tsx @@ -9,6 +9,7 @@ import { import { Text } from "react-native"; import { act, render, renderAsync } from "@testing-library/react-native"; +import { styled } from "react-native-css"; import { View } from "react-native-css/components/View"; import { registerCSS } from "react-native-css/jest"; import { useNativeVariable } from "react-native-css/native"; @@ -581,3 +582,94 @@ test("an element Activity hid follows rules that changed while it was hidden", a setViewport(originalWidth, originalHeight); } }); + +test("a media query firing after a prop update with unchanged rule observables uses the latest committed props", () => { + registerCSS(` + .audit-committed-props { height: 5px; } + @media (min-width: 600px) { .audit-committed-props[disabled] { width: 20px; } } + `); + const originalWidth = vw.get(); + const originalHeight = vh.get(); + setViewport(500, 500); + const screen = render( + , + ); + try { + // Changing style trips testGuards (forceUpdate) while stylesObs and ruleReads observables stay identical. + screen.rerender( + , + ); + act(() => { + vw.set(700); + }); + expect(screen.getByTestId("sample").props.style).toStrictEqual([ + { height: 5, width: 20 }, + { opacity: 0.5 }, + ]); + } finally { + screen.unmount(); + setViewport(originalWidth, originalHeight); + } +}); + +test("an element Activity hid after a viewport update does not spuriously re-render when shown unchanged, and still catches up when changed", async () => { + registerCSS(".audit-activity-version { width: 10vw; }"); + const originalWidth = vw.get(); + const originalHeight = vh.get(); + setViewport(500, 500); + let renders = 0; + function Probe({ style }: { style?: unknown }) { + renders += 1; + return {JSON.stringify(style)}; + } + const StyledProbe = styled(Probe); + function Sample({ mode }: { mode: "visible" | "hidden" }) { + return ( + + + + ); + } + const screen = await renderAsync(); + try { + expect(screen.getByTestId("probe").props.children).toBe('{"width":50}'); + await act(() => { + vw.set(600); + return Promise.resolve(); + }); + expect(screen.getByTestId("probe").props.children).toBe('{"width":60}'); + + await screen.rerenderAsync(); + const rendersBeforeShow = renders; + await screen.rerenderAsync(); + expect(screen.getByTestId("probe").props.children).toBe('{"width":60}'); + // Only the normal reveal render runs — no spurious styleEffect.run() catch-up render + expect(renders).toBe(rendersBeforeShow + 1); + + await screen.rerenderAsync(); + await act(() => { + vw.set(700); + return Promise.resolve(); + }); + const rendersBeforeChangedShow = renders; + await screen.rerenderAsync(); + expect(screen.getByTestId("probe").props.children).toBe('{"width":70}'); + // The reveal render already read the new value, so no catch-up render follows + expect(renders).toBe(rendersBeforeChangedShow + 1); + } finally { + await screen.unmountAsync(); + setViewport(originalWidth, originalHeight); + } +});