This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: react-native-fabric-synchronous-layout-deadlock-guardrail

React Native Fabric Synchronous Layout Deadlock Guardrail

Enforces strict isolation between asynchronous C++ Fabric shadow tree mutations and UI-thread synchronous layout queries. Prevents priority inversion and mutual-exclusion deadlocks between the native UI thread and the JS/Shadow thread during active gesture responder lifecycles and layout recalculations.

Prohibited Anti-Pattern: Synchronous DOM-style Layout Queries Inside High-Frequency Gesture or Mutation Handlers Under the Fabric Renderer

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native Fabric Synchronous Layout Deadlock Guardrail - Enforces strict isolation between asynchronous C++ Fabric shadow tree mutations and UI-thread synchronous layout queries. Prevents priority inversion and mutual-exclusion deadlocks between the native UI thread and the JS/Shadow thread during active gesture responder lifecycles and layout recalculations.
globs: src/**/*.{ts,tsx}, components/**/*.{ts,tsx}, native/**/*.{cpp,h,mm}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-fabric-synchronous-layout-deadlock-guardrail"
---

# React Native Fabric Synchronous Layout Deadlock Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Synchronous DOM-style Layout Queries Inside High-Frequency Gesture or Mutation Handlers Under the Fabric Renderer

## System Constraints
You are a Principal Mobile Architect enforcing synchronization invariants across React Native's Fabric Renderer. Fabric executes C++ Shadow Tree mutations concurrently while maintaining a single UI thread on iOS and Android. You must prevent mutual-exclusion deadlocks caused by synchronous host measurements (measure, measureInWindow, getBoundingClientRect equivalents) invoked inside high-frequency gesture responders, commit hooks, or re-render cycles that lock the Shadow Tree while awaiting UI thread dispatch.

## Strict Guidelines
- Engineers MUST ALWAYS decouple gesture position calculations from synchronous layout measurement APIs (`measure()`, `measureInWindow()`, or host component bridge calls) during active pan/scroll lifecycles.
- Engineers MUST NEVER execute synchronous UI layout measurements inside `useLayoutEffect`, high-frequency `onScroll`, or gesture responder callbacks (`PanResponder`, `GestureHandler`) while triggering concurrent React state updates.
- Engineers MUST use declarative, worklet-driven layout pipelines (`react-native-reanimated` shared values or Fabric `measure` worklets) with asynchronous boundaries to consume geometry.
- Engineers MUST wrap post-render layout queries in `requestAnimationFrame` or `InteractionManager.runAfterInteractions` when synchronous state-to-layout reconciliations cannot be handled purely inside Yoga layout passes.
- Native TurboModules and Fabric components MUST NOT synchronously block the platform UI thread waiting on `ShadowTree::commit` or `ComponentDescriptor::cloneNode` completions.

## Bad vs Good Implementations
### Synchronous Host Measurement in Gesture Callback Leading to Fabric Deadlock

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invoking `measure` inside the JS-driven `PanResponderMove` forces the host UI thread to query the current mount state while concurrently dispatching JS-thread gestures. Under Fabric's C++ concurrent layout engine, this pattern risks mutual exclusion deadlocks when Yoga layout commits compete with the platform UI view hierarchy lock.
```typescript
import React, { useRef } from 'react';
import { View, PanResponder } from 'react-native';

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

  const panResponder = PanResponder.create({
    onPanResponderMove: (_evt, gestureState) => {
      // DEADLOCK RISK: Calling synchronous native measurements while React Fabric 
      // is processing state updates or shadow tree clones blocks the UI thread
      viewRef.current?.measure((_x, _y, _width, _height, pageX, pageY) => {
        // Dispatches synchronous state changes while the shadow tree is being mutated
        console.log('Position:', pageX, pageY, gestureState.dx);
      });
    },
  });

  return <View ref={viewRef} {...panResponder.panHandlers} />;
};
```

#### Production Standard (Correct)
> **Standard**: Reanimated worklets operate directly on the UI thread without crossing the React concurrent scheduler or triggering synchronous C++ shadow tree clones. Geometry mutations bypass imperative host measurement, guaranteeing immunity to priority inversion deadlocks in Fabric.
```typescript
import React from 'react';
import { StyleSheet } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, { useAnimatedStyle, useSharedValue } from 'react-native-reanimated';

export const NonDeadlockingDraggable = () => {
  const translateX = useSharedValue(0);
  const translateY = useSharedValue(0);
  const startX = useSharedValue(0);
  const startY = useSharedValue(0);

  const panGesture = Gesture.Pan()
    .onStart(() => {
      startX.value = translateX.value;
      startY.value = translateY.value;
    })
    .onUpdate((event) => {
      // Isolated on UI Worklet thread: No synchronous C++ shadow tree locks or host bridge measurements
      translateX.value = startX.value + event.translationX;
      translateY.value = startY.value + event.translationY;
    });

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

  return (
    <GestureDetector gesture={panGesture}>
      <Animated.View style={[styles.box, animatedStyle]} />
    </GestureDetector>
  );
};

const styles = StyleSheet.create({
  box: {
    width: 100,
    height: 100,
  },
});
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native Fabric Synchronous Layout Deadlock Guardrail

React Native Fabric Synchronous Layout Deadlock Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict isolation between asynchronous C++ Fabric shadow tree mutations and UI-thread synchronous layout queries. Prevents priority inversion and mutual-exclusion deadlocks between the native UI thread and the JS/Shadow thread during active gesture responder lifecycles and layout recalculations. 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: Synchronous DOM-style Layout Queries Inside High-Frequency Gesture or Mutation Handlers Under the Fabric Renderer 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 DriftSynchronous DOM-style Layout Queries Inside High-Frequency Gesture or Mutation Handlers Under the Fabric RendererCritical
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 ALWAYS decouple gesture position calculations from synchronous layout measurement APIs (`measure()`, `measureInWindow()`, or host component bridge calls) during active pan/scroll lifecycles.

Engineers MUST ALWAYS decouple gesture position calculations from synchronous layout measurement APIs (`measure()`, `measureInWindow()`, or host component bridge calls) during active pan/scroll lifecycles.

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 NEVER execute synchronous UI layout measurements inside `useLayoutEffect`, high-frequency `onScroll`, or gesture responder callbacks (`PanResponder`, `GestureHandler`) while triggering concurrent React state updates.

Engineers MUST NEVER execute synchronous UI layout measurements inside `useLayoutEffect`, high-frequency `onScroll`, or gesture responder callbacks (`PanResponder`, `GestureHandler`) while triggering concurrent React state updates.

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 use declarative, worklet-driven layout pipelines (`react-native-reanimated` shared values or Fabric `measure` worklets) with asynchronous boundaries to consume geometry.

Engineers MUST use declarative, worklet-driven layout pipelines (`react-native-reanimated` shared values or Fabric `measure` worklets) with asynchronous boundaries to consume geometry.

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

Engineers MUST wrap post-render layout queries in `requestAnimationFrame` or `InteractionManager.runAfterInteractions` when synchronous state-to-layout reconciliations cannot be handled purely inside Yoga layout passes.

Engineers MUST wrap post-render layout queries in `requestAnimationFrame` or `InteractionManager.runAfterInteractions` when synchronous state-to-layout reconciliations cannot be handled purely inside Yoga layout passes.

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

Native TurboModules and Fabric components MUST NOT synchronously block the platform UI thread waiting on `ShadowTree

Native TurboModules and Fabric components MUST NOT synchronously block the platform UI thread waiting on `ShadowTree::commit` or `ComponentDescriptor::cloneNode` completions.

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 Fabric Synchronous Layout Deadlock Guardrail critical for AI coding assistants?

Enforces strict isolation between asynchronous C++ Fabric shadow tree mutations and UI-thread synchronous layout queries. Prevents priority inversion and mutual-exclusion deadlocks between the native UI thread and the JS/Shadow thread during active gesture responder lifecycles and layout recalculations. 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 (Synchronous DOM-style Layout Queries Inside High-Frequency Gesture or Mutation Handlers Under the Fabric Renderer) 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