This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: react19-activity-webgl-context-preservation-boundary

React 19 Activity WebGL Context Lifecycle and Resource Preservation Guardrail

Mandates explicit WebGL context preservation, tick loop suspension, and resource lifecycle management when wrapping Three.js, Babylon.js, or raw WebGL renderers inside React 19 `<Activity>` boundaries. Components hidden via the Activity API remain mounted in memory with DOM attachment preserved or detached into an offscreen state, necessitating immediate RAF cancellation, buffer preservation, and idempotent context restoration upon visibility reactivation.

Prohibited Anti-Pattern: Unbounded RAF loops and naive canvas unmount cleansers during React 19 Activity state transitions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React 19 Activity WebGL Context Lifecycle and Resource Preservation Guardrail - Mandates explicit WebGL context preservation, tick loop suspension, and resource lifecycle management when wrapping Three.js, Babylon.js, or raw WebGL renderers inside React 19 `<Activity>` boundaries. Components hidden via the Activity API remain mounted in memory with DOM attachment preserved or detached into an offscreen state, necessitating immediate RAF cancellation, buffer preservation, and idempotent context restoration upon visibility reactivation.
globs: src/**/*.{ts,tsx}, components/**/*.{ts,tsx}, features/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react19-activity-webgl-context-preservation-boundary"
---

# React 19 Activity WebGL Context Lifecycle and Resource Preservation Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unbounded RAF loops and naive canvas unmount cleansers during React 19 Activity state transitions

## System Constraints
You are a Principal Frontend Architect enforcing strict memory and hardware-acceleration invariants under React 19's `<Activity>` (formerly Offscreen) prerender API. Your mandate is to prevent GPU memory exhaustions, context-loss panics, and orphan `requestAnimationFrame` render loops when views transition between 'visible' and 'hidden' states without unmounting.

## Strict Guidelines
- Engineers MUST ALWAYS isolate WebGL canvas instances within an explicit context-preservation boundary that intercepts React 19 `Activity` mode transitions.
- Engineers MUST pause `requestAnimationFrame` loops, worker dispatchers, and physics tickers synchronously when the enclosing `<Activity mode="hidden">` boundary deactivates visibility.
- Engineers MUST NOT rely exclusively on standard component unmount cleanup functions (`useEffect` return callbacks) to release or pause WebGL resources, as hidden Activity subtrees remain mounted.
- Engineers MUST preserve GPU textures, geometry buffers, and program caches during Activity suspension while explicitly discarding transient framebuffers to prevent VRAM bloat.
- Code MUST listen to the `webglcontextlost` and `webglcontextrestored` events on canvas elements managed inside Activity boundaries, re-initializing lost shader programs idempotently on restore.
- Components NEVER execute GPU draw calls (`gl.drawArrays`, `gl.drawElements`, `renderer.render()`) while an Activity boundary's computed mode evaluates to `hidden`.

## Bad vs Good Implementations
### WebGL Context and Loop Management inside React 19 Activity

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Under React 19's `<Activity mode="hidden">`, effects do not run unmount cleanups in the traditional manner. The `requestAnimationFrame` loop executes continuously in the background, rendering to an offscreen canvas and starving the main thread and GPU of resources while risking context loss due to unbounded unthrottled draw calls.
```typescript
import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';

interface CanvasProps {
  isActive: boolean;
}

export const BadWebGLView: React.FC<CanvasProps> = ({ isActive }) => {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  // ANTI-PATTERN: Relies solely on unmount cleanup.
  // In React 19 <Activity mode="hidden">, this component remains mounted.
  // The animation frame loop continues running in the background, consuming 100% GPU/CPU.
  useEffect(() => {
    if (!canvasRef.current) return;
    const renderer = new THREE.WebGLRenderer({ canvas: canvasRef.current });
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
    
    let frameId: number;
    const animate = () => {
      frameId = requestAnimationFrame(animate);
      renderer.render(scene, camera);
    };
    animate();

    return () => {
      cancelAnimationFrame(frameId);
      renderer.dispose();
    };
  }, []);

  return <canvas ref={canvasRef} />;
};
```

#### Production Standard (Correct)
> **Standard**: Decouples the WebGL context initialization lifecycle from the React 19 Activity visibility mode. When mode shifts to 'hidden', the animation loop halts cleanly via `cancelAnimationFrame`, preventing GPU utilization and avoiding context thrashing while retaining VRAM state (buffers, textures). Context restoration listeners guard against device loss during background suspension.
```typescript
import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';

interface WebGLActivityBoundaryProps {
  mode: 'visible' | 'hidden';
  children?: React.ReactNode;
}

export const SafeWebGLViewport: React.FC<{ mode: 'visible' | 'hidden' }> = ({ mode }) => {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
  const rafIdRef = useRef<number | null>(null);
  const sceneRef = useRef<THREE.Scene | null>(null);
  const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);

  // Initialize Engine & Handle Context Loss Lifecycle
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const renderer = new THREE.WebGLRenderer({
      canvas,
      powerPreference: 'high-performance',
      preserveDrawingBuffer: false,
    });
    rendererRef.current = renderer;
    sceneRef.current = new THREE.Scene();
    cameraRef.current = new THREE.PerspectiveCamera(75, canvas.clientWidth / canvas.clientHeight, 0.1, 1000);

    const handleContextLost = (e: Event) => {
      e.preventDefault();
      if (rafIdRef.current !== null) {
        cancelAnimationFrame(rafIdRef.current);
        rafIdRef.current = null;
      }
    };

    const handleContextRestored = () => {
      // Recompile shaders and restore static GPU memory
      renderer.resetState();
    };

    canvas.addEventListener('webglcontextlost', handleContextLost, false);
    canvas.addEventListener('webglcontextrestored', handleContextRestored, false);

    return () => {
      canvas.removeEventListener('webglcontextlost', handleContextLost);
      canvas.removeEventListener('webglcontextrestored', handleContextRestored);
      if (rafIdRef.current !== null) cancelAnimationFrame(rafIdRef.current);
      renderer.dispose();
      rendererRef.current = null;
    };
  }, []);

  // React 19 Activity Visibility Sync: Throttle loop without destroying GPU context
  useEffect(() => {
    if (mode === 'hidden') {
      if (rafIdRef.current !== null) {
        cancelAnimationFrame(rafIdRef.current);
        rafIdRef.current = null;
      }
      return;
    }

    let running = true;
    const renderLoop = () => {
      if (!running || !rendererRef.current || !sceneRef.current || !cameraRef.current) return;
      rendererRef.current.render(sceneRef.current, cameraRef.current);
      rafIdRef.current = requestAnimationFrame(renderLoop);
    };

    rafIdRef.current = requestAnimationFrame(renderLoop);

    return () => {
      running = false;
      if (rafIdRef.current !== null) {
        cancelAnimationFrame(rafIdRef.current);
        rafIdRef.current = null;
      }
    };
  }, [mode]);

  return <canvas ref={canvasRef} style={{ display: mode === 'hidden' ? 'none' : 'block' }} />;
};
```

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 19 Activity WebGL Context Lifecycle and Resource Preservation Guardrail

React 19 Activity WebGL Context Lifecycle and Resource Preservation Guardrail defines an industrial-grade behavioral standard for frontend engineering. Mandates explicit WebGL context preservation, tick loop suspension, and resource lifecycle management when wrapping Three.js, Babylon.js, or raw WebGL renderers inside React 19 `<Activity>` boundaries. Components hidden via the Activity API remain mounted in memory with DOM attachment preserved or detached into an offscreen state, necessitating immediate RAF cancellation, buffer preservation, and idempotent context restoration upon visibility reactivation. 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: Unbounded RAF loops and naive canvas unmount cleansers during React 19 Activity state transitions 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 DriftUnbounded RAF loops and naive canvas unmount cleansers during React 19 Activity state transitionsCritical
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 isolate WebGL canvas instances within an explicit context-preservation boundary that intercepts React 19 `Activity` mode transitions.

Engineers MUST ALWAYS isolate WebGL canvas instances within an explicit context-preservation boundary that intercepts React 19 `Activity` mode transitions.

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 pause `requestAnimationFrame` loops, worker dispatchers, and physics tickers synchronously when the enclosing `<Activity mode="hidden">` boundary deactivates visibility.

Engineers MUST pause `requestAnimationFrame` loops, worker dispatchers, and physics tickers synchronously when the enclosing `<Activity mode="hidden">` boundary deactivates visibility.

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 NOT rely exclusively on standard component unmount cleanup functions (`useEffect` return callbacks) to release or pause WebGL resources, as hidden Activity subtrees remain mounted.

Engineers MUST NOT rely exclusively on standard component unmount cleanup functions (`useEffect` return callbacks) to release or pause WebGL resources, as hidden Activity subtrees remain mounted.

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 preserve GPU textures, geometry buffers, and program caches during Activity suspension while explicitly discarding transient framebuffers to prevent VRAM bloat.

Engineers MUST preserve GPU textures, geometry buffers, and program caches during Activity suspension while explicitly discarding transient framebuffers to prevent VRAM bloat.

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 MUST listen to the `webglcontextlost` and `webglcontextrestored` events on canvas elements managed inside Activity boundaries, re-initializing lost shader programs idempotently on restore.

Code MUST listen to the `webglcontextlost` and `webglcontextrestored` events on canvas elements managed inside Activity boundaries, re-initializing lost shader programs idempotently on restore.

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.
6

Components NEVER execute GPU draw calls (`gl.drawArrays`, `gl.drawElements`, `renderer.render()`) while an Activity boundary's computed mode evaluates to `hidden`.

Components NEVER execute GPU draw calls (`gl.drawArrays`, `gl.drawElements`, `renderer.render()`) while an Activity boundary's computed mode evaluates to `hidden`.

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 19 Activity WebGL Context Lifecycle and Resource Preservation Guardrail critical for AI coding assistants?

Mandates explicit WebGL context preservation, tick loop suspension, and resource lifecycle management when wrapping Three.js, Babylon.js, or raw WebGL renderers inside React 19 `<Activity>` boundaries. Components hidden via the Activity API remain mounted in memory with DOM attachment preserved or detached into an offscreen state, necessitating immediate RAF cancellation, buffer preservation, and idempotent context restoration upon visibility reactivation. 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 (Unbounded RAF loops and naive canvas unmount cleansers during React 19 Activity state transitions) 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 FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

React