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

React Native 0.77+ Bridgeless C++ JSI Memory Lifecycle Guardrail

Enforces strict memory ownership boundaries between C++ HostObjects and the Hermes JavaScript Garbage Collector under React Native 0.77+ Bridgeless Architecture. Prevents SIGSEGV crashes, use-after-free conditions, and uncollectable GC roots during asynchronous native callbacks across rapid unmount/mount component lifecycles.

Prohibited Anti-Pattern: Dangling C++ JSI References and Stale Callbacks Outliving Unmounted React Fiber Nodes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.77+ Bridgeless C++ JSI Memory Lifecycle Guardrail - Enforces strict memory ownership boundaries between C++ HostObjects and the Hermes JavaScript Garbage Collector under React Native 0.77+ Bridgeless Architecture. Prevents SIGSEGV crashes, use-after-free conditions, and uncollectable GC roots during asynchronous native callbacks across rapid unmount/mount component lifecycles.
globs: src/**/*.{ts,tsx}, ios/**/*.{h,m,mm,cpp}, android/src/main/jni/**/*.{h,cpp}, cpp/**/*.{h,cpp}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-jsi-lifecycle-guardrail"
---

# React Native 0.77+ Bridgeless C++ JSI Memory Lifecycle Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Dangling C++ JSI References and Stale Callbacks Outliving Unmounted React Fiber Nodes

## System Constraints
You are a Principal Mobile Architect enforcing C++ JSI memory and lifecycle safety in React Native 0.77+ Bridgeless Architecture. You must ensure that no jsi::Value, jsi::Object, or jsi::Function is retained asynchronously past the lifespan of its originating Hermes Runtime or the React component mounting context. Mandate RAII, std::weak_ptr, thread-safe CallInvoker dispatching, and deterministic unregister hooks on cleanup.

## Strict Guidelines
- Engineers MUST ALWAYS capture C++ HostObjects via std::weak_ptr in asynchronous callbacks and dispatch through facebook::react::CallInvoker::invokeAsync.
- Engineers MUST NEVER retain raw jsi::Value, jsi::Object, or jsi::Function pointers across asynchronous dispatch boundaries without wrapping them in jsi::Value or using an explicit cancellation token.
- Engineers MUST ALWAYS invalidate and release native JSI listeners within useEffect/useLayoutEffect cleanup return closures to prevent uncollectable root references in Hermes GC.
- Native C++ JSI implementations MUST verify that the jsi::Runtime instance is valid and not shutting down prior to invoking JavaScript callbacks from secondary threads.
- Components NEVER trigger native subscription allocations without storing a deterministic cleanup unregister token in a useRef or useEffect destructor.

## Bad vs Good Implementations
### JSI Event Subscription Lifecycle in Bridgeless React Native

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing a plain JavaScript closure directly to a C++ JSI interface without acquiring an unsubscription token causes the native host to hold a persistent jsi::Function reference. If the component unmounts and Hermes runs garbage collection while C++ invokes the closure, the application crashes with a fatal SIGSEGV (use-after-free).
```typescript
import { useEffect } from 'react';

declare const NativeSensorJSI: {
  subscribe: (callback: (data: number) => void) => void;
};

export function SensorMonitor() {
  useEffect(() => {
    // ANTI-PATTERN: Passing callback directly to JSI without unregister handle
    // When unmounted rapidly, C++ attempts to invoke a garbage-collected jsi::Function
    NativeSensorJSI.subscribe((data) => {
      console.log('Received sensor data:', data);
    });
  }, []);

  return null;
}
```

#### Production Standard (Correct)
> **Standard**: Maintains an explicit lifecycle token (`subscriptionRef`) and safely tears down the native listener within the `useEffect` cleanup return. Pairing an `isMounted` guard with deterministic C++ native unregistration cleans up HostObject references and prevents execution against invalid Hermes GC scopes.
```typescript
import { useEffect, useRef } from 'react';

interface SensorSubscription {
  remove: () => void;
}

declare const NativeSensorJSI: {
  subscribe: (callback: (data: number) => void) => SensorSubscription;
};

export function SensorMonitor() {
  const subscriptionRef = useRef<SensorSubscription | null>(null);

  useEffect(() => {
    let isMounted = true;

    subscriptionRef.current = NativeSensorJSI.subscribe((data: number) => {
      if (!isMounted) {
        return;
      }
      console.log('Received sensor data:', data);
    });

    return () => {
      isMounted = false;
      if (subscriptionRef.current) {
        subscriptionRef.current.remove();
        subscriptionRef.current = null;
      }
    };
  }, []);

  return null;
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Native 0.77+ Bridgeless C++ JSI Memory Lifecycle Guardrail

React Native 0.77+ Bridgeless C++ JSI Memory Lifecycle Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory ownership boundaries between C++ HostObjects and the Hermes JavaScript Garbage Collector under React Native 0.77+ Bridgeless Architecture. Prevents SIGSEGV crashes, use-after-free conditions, and uncollectable GC roots during asynchronous native callbacks across rapid unmount/mount component lifecycles. 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: Dangling C++ JSI References and Stale Callbacks Outliving Unmounted React Fiber Nodes 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 DriftDangling C++ JSI References and Stale Callbacks Outliving Unmounted React Fiber NodesCritical
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 capture C++ HostObjects via std

Engineers MUST ALWAYS capture C++ HostObjects via std::weak_ptr in asynchronous callbacks and dispatch through facebook::react::CallInvoker::invokeAsync.

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 retain raw jsi

Engineers MUST NEVER retain raw jsi::Value, jsi::Object, or jsi::Function pointers across asynchronous dispatch boundaries without wrapping them in jsi::Value or using an explicit cancellation token.

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 ALWAYS invalidate and release native JSI listeners within useEffect/useLayoutEffect cleanup return closures to prevent uncollectable root references in Hermes GC.

Engineers MUST ALWAYS invalidate and release native JSI listeners within useEffect/useLayoutEffect cleanup return closures to prevent uncollectable root references in Hermes GC.

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

Native C++ JSI implementations MUST verify that the jsi

Native C++ JSI implementations MUST verify that the jsi::Runtime instance is valid and not shutting down prior to invoking JavaScript callbacks from secondary threads.

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

Components NEVER trigger native subscription allocations without storing a deterministic cleanup unregister token in a useRef or useEffect destructor.

Components NEVER trigger native subscription allocations without storing a deterministic cleanup unregister token in a useRef or useEffect destructor.

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.77+ Bridgeless C++ JSI Memory Lifecycle Guardrail critical for AI coding assistants?

Enforces strict memory ownership boundaries between C++ HostObjects and the Hermes JavaScript Garbage Collector under React Native 0.77+ Bridgeless Architecture. Prevents SIGSEGV crashes, use-after-free conditions, and uncollectable GC roots during asynchronous native callbacks across rapid unmount/mount component lifecycles. 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 (Dangling C++ JSI References and Stale Callbacks Outliving Unmounted React Fiber Nodes) 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