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

React 19 Activity API Offscreen Fiber State Preservation and Resource Management

Establishes production invariants for React 19 Activity (Offscreen) boundary usage during multi-tab and multi-view navigation. Enforces deterministic DOM detachment, fiber cache retention, and strict cleanup of background render timers, web workers, and WebGL contexts to prevent memory bloat and CPU starvation.

Prohibited Anti-Pattern: Uncontrolled Background Fiber Execution and Memory Leakage via Hidden React 19 Activity Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React 19 Activity API Offscreen Fiber State Preservation and Resource Management - Establishes production invariants for React 19 Activity (Offscreen) boundary usage during multi-tab and multi-view navigation. Enforces deterministic DOM detachment, fiber cache retention, and strict cleanup of background render timers, web workers, and WebGL contexts to prevent memory bloat and CPU starvation.
globs: src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react19-activity-offscreen-state-preservation-standard"
---

# React 19 Activity API Offscreen Fiber State Preservation and Resource Management

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Uncontrolled Background Fiber Execution and Memory Leakage via Hidden React 19 Activity Boundaries

## System Constraints
You are a Principal Software Architect enforcing zero-leak React 19 Activity (Offscreen) fiber retention patterns. In React 19, the `<Activity mode="hidden" | "visible">` API preserves component state, DOM elements, and internal fibers without unmounting. However, failure to isolate compute cycles, requestAnimationFrame loops, WebSockets, or GPU buffers within hidden activity boundaries leads to catastrophic background resource exhaustion. You must enforce explicit synchronization between activity visibility, passive effect pausing, and eviction policies for background tabs.

## Strict Guidelines
- Engineers MUST ALWAYS suspend active polling, animation loops (requestAnimationFrame), and continuous worker dispatches when an `<Activity>` mode shifts to 'hidden'.
- Engineers MUST NOT tear down local UI state or unmount subtrees via conditional rendering (`{isActive && <Component />}`) when tab state retention across route changes is required.
- Code SHOULD wrap non-critical sub-trees inside React 19 `<Activity mode={isActive ? 'visible' : 'hidden'}>` to preserve scroll coordinates, input buffers, and ephemeral client states across view swaps.
- Components MUST decouple memory-heavy ephemeral allocations (e.g., ArrayBuffers, WebGL framebuffers, large canvas contexts) when mode transitions to 'hidden' using specialized visibility awareness hooks.
- Services MUST implement a deterministic Least Recently Used (LRU) background tab culling policy to force full unmounting and fiber reclamation once background Activity instances exceed defined memory thresholds.
- Components NEVER assume `useEffect` cleanup represents a complete fiber destruction; in Activity hidden mode, effects clean up but component state and ref allocations remain alive in memory.

## Bad vs Good Implementations
### Background Fiber Resource Drain vs Controlled Activity Suspension

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When the Activity mode is 'hidden', React 19 runs passive effect cleanups (useEffect), but re-runs them immediately when transitioning to visible. If effects are not explicitly guarded against hidden mode or if background activities are unbounded without an LRU eviction strategy, the browser retains arbitrary DOM nodes, closures, and unmanaged external event listeners without bounds.
```typescript
import React, { useState, useEffect } from 'react';
// React 19 experimental / unstable Activity import
import { Activity } from 'react';

interface TabProps {
  activeTabId: string;
}

export const TabContainer: React.FC<TabProps> = ({ activeTabId }) => {
  return (
    <div>
      {/* ANTI-PATTERN: Heavy dashboard remains running timers/raf when hidden */}
      <Activity mode={activeTabId === 'analytics' ? 'visible' : 'hidden'}>
        <HeavyAnalyticsDashboard />
      </Activity>
      <Activity mode={activeTabId === 'settings' ? 'visible' : 'hidden'}>
        <SettingsView />
      </Activity>
    </div>
  );
};

const HeavyAnalyticsDashboard: React.FC = () => {
  const [metrics, setMetrics] = useState<number[]>([]);

  useEffect(() => {
    // Bug: Interval or socket connection continues consuming CPU/network
    // even when the Activity component is hidden by the parent boundary,
    // or repeatedly tears down without checkpointing buffer state.
    const interval = setInterval(() => {
      setMetrics(prev => [...prev.slice(-99), Math.random() * 100]);
    }, 100);
    return () => clearInterval(interval);
  }, []);

  return <div>Metrics count: {metrics.length}</div>;
};
```

#### Production Standard (Correct)
> **Standard**: Provides an explicit `ActivityContext` to propagate visibility state down the fiber subtree. Heavy resources, animation frames, and continuous workers are paused deterministically when the parent Activity is hidden, while maintaining React fiber state and DOM position intact for zero-latency resumption.
```typescript
import React, { createContext, useContext, useMemo, useEffect, useRef } from 'react';
import { Activity } from 'react';

interface ActivityContextValue {
  isVisible: boolean;
}

const ActivityContext = createContext<ActivityContextValue>({ isVisible: true });

interface ManagedTabProps {
  id: string;
  activeTabId: string;
  children: React.ReactNode;
}

export const ManagedActivityTab: React.FC<ManagedTabProps> = ({
  id,
  activeTabId,
  children
}) => {
  const isVisible = id === activeTabId;
  const contextValue = useMemo(() => ({ isVisible }), [isVisible]);

  return (
    <Activity mode={isVisible ? 'visible' : 'hidden'}>
      <ActivityContext.Provider value={contextValue}>
        {children}
      </ActivityContext.Provider>
    </Activity>
  );
};

export const useActivityState = (): ActivityContextValue => {
  return useContext(ActivityContext);
};

export const HighThroughputAnalytics: React.FC = () => {
  const { isVisible } = useActivityState();
  const animationRef = useRef<number | null>(null);
  const dataBufferRef = useRef<Float64Array>(new Float64Array(1000));

  useEffect(() => {
    if (!isVisible) {
      // Halt CPU loops and purge large transient allocations
      if (animationRef.current !== null) {
        cancelAnimationFrame(animationRef.current);
        animationRef.current = null;
      }
      return;
    }

    const renderLoop = () => {
      // Execute high-frequency canvas/state updates only when visible
      animationRef.current = requestAnimationFrame(renderLoop);
    };
    animationRef.current = requestAnimationFrame(renderLoop);

    return () => {
      if (animationRef.current !== null) {
        cancelAnimationFrame(animationRef.current);
        animationRef.current = null;
      }
    };
  }, [isVisible]);

  return <canvas id="analytics-canvas" />;
};
```

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 19 Activity API Offscreen Fiber State Preservation and Resource Management

React 19 Activity API Offscreen Fiber State Preservation and Resource Management defines an industrial-grade behavioral standard for frontend engineering. Establishes production invariants for React 19 Activity (Offscreen) boundary usage during multi-tab and multi-view navigation. Enforces deterministic DOM detachment, fiber cache retention, and strict cleanup of background render timers, web workers, and WebGL contexts to prevent memory bloat and CPU starvation. 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: Uncontrolled Background Fiber Execution and Memory Leakage via Hidden React 19 Activity Boundaries 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 DriftUncontrolled Background Fiber Execution and Memory Leakage via Hidden React 19 Activity BoundariesCritical
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 suspend active polling, animation loops (requestAnimationFrame), and continuous worker dispatches when an `<Activity>` mode shifts to 'hidden'.

Engineers MUST ALWAYS suspend active polling, animation loops (requestAnimationFrame), and continuous worker dispatches when an `<Activity>` mode shifts 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.
2

Engineers MUST NOT tear down local UI state or unmount subtrees via conditional rendering (`{isActive && <Component />}`) when tab state retention across route changes is required.

Engineers MUST NOT tear down local UI state or unmount subtrees via conditional rendering (`{isActive && <Component />}`) when tab state retention across route changes is required.

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

Code SHOULD wrap non-critical sub-trees inside React 19 `<Activity mode={isActive ? 'visible'

Code SHOULD wrap non-critical sub-trees inside React 19 `<Activity mode={isActive ? 'visible' : 'hidden'}>` to preserve scroll coordinates, input buffers, and ephemeral client states across view swaps.

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 MUST decouple memory-heavy ephemeral allocations (e.g., ArrayBuffers, WebGL framebuffers, large canvas contexts) when mode transitions to 'hidden' using specialized visibility awareness hooks.

Components MUST decouple memory-heavy ephemeral allocations (e.g., ArrayBuffers, WebGL framebuffers, large canvas contexts) when mode transitions to 'hidden' using specialized visibility awareness hooks.

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

Services MUST implement a deterministic Least Recently Used (LRU) background tab culling policy to force full unmounting and fiber reclamation once background Activity instances exceed defined memory thresholds.

Services MUST implement a deterministic Least Recently Used (LRU) background tab culling policy to force full unmounting and fiber reclamation once background Activity instances exceed defined memory thresholds.

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 assume `useEffect` cleanup represents a complete fiber destruction

Components NEVER assume `useEffect` cleanup represents a complete fiber destruction; in Activity hidden mode, effects clean up but component state and ref allocations remain alive in memory.

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 API Offscreen Fiber State Preservation and Resource Management critical for AI coding assistants?

Establishes production invariants for React 19 Activity (Offscreen) boundary usage during multi-tab and multi-view navigation. Enforces deterministic DOM detachment, fiber cache retention, and strict cleanup of background render timers, web workers, and WebGL contexts to prevent memory bloat and CPU starvation. 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 (Uncontrolled Background Fiber Execution and Memory Leakage via Hidden React 19 Activity Boundaries) 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