Skip to content

feat: lexically scoped React Server Components#355

Merged
lazarv merged 1 commit intomainfrom
feat/lexically-scoped-react-server-components
Mar 11, 2026
Merged

feat: lexically scoped React Server Components#355
lazarv merged 1 commit intomainfrom
feat/lexically-scoped-react-server-components

Conversation

@lazarv
Copy link
Copy Markdown
Owner

@lazarv lazarv commented Mar 11, 2026

Lexically Scoped React Server Components

Summary

This PR introduces inline "use client" and "use server" directives at the function level, eliminating the requirement that these directives apply to entire modules. Developers can now define client components and server functions directly inside any function body — at arbitrary nesting depths — within a single file.

No other React framework currently supports this capability.

Motivation

In the standard RSC model, "use client" and "use server" are module-level declarations. This forces developers to split tightly-coupled server and client logic across separate files, leading to:

  • File proliferation — a server component with one client button requires at least two files.
  • Artificial indirection — the logical unit ("this server page contains this interactive widget") is scattered across the filesystem.
  • Impossible compositions — a server function that dynamically constructs and returns different client components cannot exist, since they must live in separate modules.

What's New

Inline "use client" inside server components

import { useState } from "react";

function Counter() {
  "use client";
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

export default function Page() {
  return <Counter />;
}

Inline "use server" inside client components

"use client";
import { useState } from "react";

export default function LikeButton() {
  async function like() {
    "use server";
    await db.likes.increment();
  }
  const [liked, setLiked] = useState(false);
  return <button onClick={() => { like(); setLiked(true); }}>{liked ? "❤️" : "🤍"}</button>;
}

Arbitrary nesting (server → client → server → …)

Directives can alternate at any depth. A server component can define an inline client component, which itself defines an inline server function, and so on.

Lexical scope capture

Variables from parent scopes are automatically forwarded to extracted modules:

  • Client components: captured variables become destructured props, passed via createElement wrappers at the call site.
  • Server functions: captured variables become Function.prototype.bind arguments prepended to the function parameters.

Module state sharing

Top-level declarations (constants, mutable variables, class instances) are not duplicated into extracted modules. Instead, extracted virtual modules import them from the original module, preserving identity and mutation semantics.

Architecture

The implementation consists of three components:

Component Role
use-directive-inline.mjs Core Vite plugin. Performs AST analysis, outermost-first multi-pass extraction, virtual module serving, and source transformation. Generic over directive type.
use-client-inline.mjs Configuration for "use client". Defines how captured variables become destructured props and how call sites become createElement wrappers.
use-server-inline.mjs Configuration for "use server". Defines how captured variables become .bind() arguments and how call sites become direct references.

The plugin is instantiated once with both configs and registered as a single Vite plugin (react-server:use-directive-inline).

Extraction algorithm

  1. Parse the source file and find all functions containing a directive in their body.
  2. Outermost-first: only extract the outermost directive functions across all directive types. Inner directives are handled in subsequent passes when the extracted virtual module is itself transformed.
  3. For each outermost directive function:
    • Detect captured scope variables (not imports, not top-level declarations, not the function's own locals).
    • Generate a virtual module (file.jsx?use-client-inline=FnName or ?use-server-inline=FnName) containing the extracted function with its directive, necessary imports, and captured variable injection.
    • Replace the original function in the source with an import from the virtual module (or a createElement wrapper / .bind() call if captured variables are present).
  4. Remove unused imports from the original module.
  5. Export top-level declarations used by extracted functions so virtual modules can import them.
  6. Cache extracted modules for consistent resolution across resolveId / load / transform lifecycle.

Build integration

  • The use-client.mjs plugin's transform filter was updated to match query-parameterized module IDs (/\.m?[jt]sx?(\?.*)?$/).
  • manifest.mjs now handles virtual modules with query parameters, correctly resolving file paths by stripping queries before realpathSync and re-appending them for consistent key generation.
  • A second pass in manifest.mjs processes buildClientManifest entries that only appear as dynamic imports in the SSR build (inline "use client" modules).
  • Both client.mjs and server.mjs build configurations register the unified useDirectiveInline plugin.

@cloudflare-workers-and-pages
Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
react-server-docs 30dd0d6 Mar 11 2026, 07:55 AM

@lazarv lazarv merged commit 55ac332 into main Mar 11, 2026
57 checks passed
@lazarv lazarv deleted the feat/lexically-scoped-react-server-components branch March 11, 2026 08:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant