This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: rn-fabric-shadow-tree-mutex-boundary

React Native 0.78 Fabric Shadow Tree Synchronous Mutex Boundary Isolation

Enforces strict isolation between Fabric C++ Shadow Tree synchronous layout measurements and JSI native module invocations. Prevents lock contention and dropped frames on 120Hz ProMotion displays (8.33ms frame deadline) caused by thread priority inversions between the React Native UI thread, JS thread, and Shadow Tree mutation mutex.

Prohibited Anti-Pattern: Contending Fabric Shadow Tree Mutexes via Interleaved Synchronous Measurements and JSI Invocations in 120Hz Animation Loops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.78 Fabric Shadow Tree Synchronous Mutex Boundary Isolation - Enforces strict isolation between Fabric C++ Shadow Tree synchronous layout measurements and JSI native module invocations. Prevents lock contention and dropped frames on 120Hz ProMotion displays (8.33ms frame deadline) caused by thread priority inversions between the React Native UI thread, JS thread, and Shadow Tree mutation mutex.
globs: src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rn-fabric-shadow-tree-mutex-boundary"
---

# React Native 0.78 Fabric Shadow Tree Synchronous Mutex Boundary Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Contending Fabric Shadow Tree Mutexes via Interleaved Synchronous Measurements and JSI Invocations in 120Hz Animation Loops

## System Constraints
You are a Principal Mobile Architect specializing in React Native 0.78 internals, the Fabric New Architecture, and C++ TurboModules. Mandate synchronous mutex boundary isolation between Fabric Shadow Tree layout queries and asynchronous JSI native calls to prevent frame drops on high-refresh-rate displays.

## Strict Guidelines
- Engineers MUST NOT invoke synchronous layout queries (e.g., ref.measure, UIManager.measure, measureInWindow) directly inside high-frequency gesture updates or animation frames that simultaneously dispatch JSI TurboModule methods.
- Engineers MUST decouple layout metrics acquisition from the 8.33ms render loop by caching values in Reanimated SharedValues during onLayout or layout effects.
- Engineers MUST execute direct Fabric C++ Shadow Tree layout traversals exclusively inside UI worklets using react-native-reanimated's measure() instead of crossing the JS-to-native synchronous bridge.
- Components NEVER execute synchronous bridge calls during continuous 120Hz gestures (e.g., pan, pinch, scroll) to eliminate thread contention on the UI/ShadowTree mutex lock.
- Code SHOULD buffer and batch JSI native module invocations using requestAnimationFrame or microtask boundaries when calculating dynamic node repositioning.

## Bad vs Good Implementations
### Preventing Mutex Contention During Continuous 120Hz Pan Gestures

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling ref.measure creates a synchronous callback across threads while invoking synchronous JSI methods inside a 120Hz onUpdate gesture callback. In React Native 0.78 Fabric, this locks the C++ Shadow Tree mutex and causes immediate thread contention, causing frame drops on ProMotion displays.
```typescript
import React, { useRef } from 'react';
import { View } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import { NativeHapticFeedbackJSI } from 'native-haptics-turbomodule';

export const DraggableCard = () => {
  const viewRef = useRef<View>(null);

  const panGesture = Gesture.Pan().onUpdate((event) => {
    // ANTI-PATTERN: Synchronously measuring host component during high-frequency gesture
    // while concurrently triggering a synchronous JSI TurboModule call.
    // Fabric's Shadow Tree Mutex is contested by the synchronous layout measurement
    // while the JSI call blocks the JS thread, starving the 8.33ms ProMotion render pipeline.
    viewRef.current?.measure((x, y, width, height, pageX, pageY) => {
      if (event.translationY > 100) {
        NativeHapticFeedbackJSI.triggerImpactSync('heavy');
      }
    });
  });

  return (
    <GestureDetector gesture={panGesture}>
      <View ref={viewRef} style={{ width: 100, height: 100, backgroundColor: 'blue' }} />
    </GestureDetector>
  );
};
```

#### Production Standard (Correct)
> **Standard**: The good pattern utilizes `useAnimatedRef` with Reanimated's worklet-native `measure()` function, executing layout queries entirely on the UI thread without crossing the legacy bridge. JSI side-effects are decoupled using `runOnJS` and debounced through shared state, leaving the Fabric Shadow Tree mutex unblocked.
```typescript
import React from 'react';
import Animated, {
  useAnimatedRef,
  useAnimatedStyle,
  useSharedValue,
  useAnimatedReaction,
  measure,
  runOnJS,
} from 'react-native-reanimated';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import { NativeHapticFeedbackJSI } from 'native-haptics-turbomodule';

const triggerHapticAsync = () => {
  'worklet';
  runOnJS(NativeHapticFeedbackJSI.triggerImpactAsync)('heavy');
};

export const DraggableCard = () => {
  const animatedRef = useAnimatedRef<Animated.View>();
  const translateY = useSharedValue(0);
  const hasTriggeredHaptic = useSharedValue(false);

  const panGesture = Gesture.Pan()
    .onUpdate((event) => {
      translateY.value = event.translationY;
    })
    .onEnd(() => {
      translateY.value = 0;
      hasTriggeredHaptic.value = false;
    });

  useAnimatedReaction(
    () => translateY.value,
    (currentY) => {
      // Isolated on UI thread: Fabric UI worklet measure isolates the Shadow Tree query
      const layout = measure(animatedRef);
      if (layout && currentY > 100 && !hasTriggeredHaptic.value) {
        hasTriggeredHaptic.value = true;
        triggerHapticAsync();
      }
    },
    [animatedRef]
  );

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateY: translateY.value }],
  }));

  return (
    <GestureDetector gesture={panGesture}>
      <Animated.View ref={animatedRef} style={[{ width: 100, height: 100, backgroundColor: 'blue' }, animatedStyle]} />
    </GestureDetector>
  );
};
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native 0.78 Fabric Shadow Tree Synchronous Mutex Boundary Isolation

React Native 0.78 Fabric Shadow Tree Synchronous Mutex Boundary Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict isolation between Fabric C++ Shadow Tree synchronous layout measurements and JSI native module invocations. Prevents lock contention and dropped frames on 120Hz ProMotion displays (8.33ms frame deadline) caused by thread priority inversions between the React Native UI thread, JS thread, and Shadow Tree mutation mutex. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Contending Fabric Shadow Tree Mutexes via Interleaved Synchronous Measurements and JSI Invocations in 120Hz Animation Loops Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftContending Fabric Shadow Tree Mutexes via Interleaved Synchronous Measurements and JSI Invocations in 120Hz Animation LoopsCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST NOT invoke synchronous layout queries (e.g., ref.measure, UIManager.measure, measureInWindow) directly inside high-frequency gesture updates or animation frames that simultaneously dispatch JSI TurboModule methods.

Engineers MUST NOT invoke synchronous layout queries (e.g., ref.measure, UIManager.measure, measureInWindow) directly inside high-frequency gesture updates or animation frames that simultaneously dispatch JSI TurboModule methods.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST decouple layout metrics acquisition from the 8.33ms render loop by caching values in Reanimated SharedValues during onLayout or layout effects.

Engineers MUST decouple layout metrics acquisition from the 8.33ms render loop by caching values in Reanimated SharedValues during onLayout or layout effects.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST execute direct Fabric C++ Shadow Tree layout traversals exclusively inside UI worklets using react-native-reanimated's measure() instead of crossing the JS-to-native synchronous bridge.

Engineers MUST execute direct Fabric C++ Shadow Tree layout traversals exclusively inside UI worklets using react-native-reanimated's measure() instead of crossing the JS-to-native synchronous bridge.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Components NEVER execute synchronous bridge calls during continuous 120Hz gestures (e.g., pan, pinch, scroll) to eliminate thread contention on the UI/ShadowTree mutex lock.

Components NEVER execute synchronous bridge calls during continuous 120Hz gestures (e.g., pan, pinch, scroll) to eliminate thread contention on the UI/ShadowTree mutex lock.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Code SHOULD buffer and batch JSI native module invocations using requestAnimationFrame or microtask boundaries when calculating dynamic node repositioning.

Code SHOULD buffer and batch JSI native module invocations using requestAnimationFrame or microtask boundaries when calculating dynamic node repositioning.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is React Native 0.78 Fabric Shadow Tree Synchronous Mutex Boundary Isolation critical for AI coding assistants?

Enforces strict isolation between Fabric C++ Shadow Tree synchronous layout measurements and JSI native module invocations. Prevents lock contention and dropped frames on 120Hz ProMotion displays (8.33ms frame deadline) caused by thread priority inversions between the React Native UI thread, JS thread, and Shadow Tree mutation mutex. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Contending Fabric Shadow Tree Mutexes via Interleaved Synchronous Measurements and JSI Invocations in 120Hz Animation Loops) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

React