Skip to content

Conversation

@everettbu
Copy link

@everettbu everettbu commented Jan 16, 2026

Mirror of facebook/react#35537
Original author: josephsavona


A whole bunch of changes to snap aimed at making it more usable for humans and agents. Here's the new CLI interface:

node dist/main.js --help
Options:
      --version         Show version number                            [boolean]
      --sync            Run compiler in main thread (instead of using worker
                        threads or subprocesses). Defaults to false.
                                                      [boolean] [default: false]
      --worker-threads  Run compiler in worker threads (instead of
                        subprocesses). Defaults to true.
                                                       [boolean] [default: true]
      --help            Show help                                      [boolean]
  -w, --watch           Run compiler in watch mode, re-running after changes
                                                                       [boolean]
  -u, --update          Update fixtures                                [boolean]
  -p, --pattern         Optional glob pattern to filter fixtures (e.g.,
                        "error.*", "use-memo")                          [string]
  -d, --debug           Enable debug logging to print HIR for each pass[boolean]

Key changes:

  • Added abbreviations for common arguments
  • No more testfilter.txt! Filtering/debugging works more like Jest, see below.
  • The --debug flag (-d) controls whether to emit debug information. In watch mode, this flag sets the initial debug value, and it can be toggled by pressing the 'd' key while watching.
  • The --pattern flag (-p) sets a filter pattern. In watch mode, this flag sets the initial filter. It can be changed by pressing 'p' and typing a new pattern, or pressing 'a' to switch to running all tests.
  • As before, we only actually enable debugging if debug mode is enabled and there is only one test selected.

Stack created with Sapling. Best reviewed with ReviewStack.

  • #35539
  • -> #35537
  • #35523
  • #35298

# Summary

note: This implements the idea discussed in reactwg/react#389 (comment)

This is a large PR that significantly changes our impurity and ref validation to address multiple issues. The goal is to reduce false positives and make the errors we do report more actionable.

## Validating Against Impure Values In Render

Currently we create `Impure` effects for impure functions like `Date.now()` or `Math.random()`, and then throw if the effect is reachable during render. However, impurity is a property of the resulting value: if the value isn't accessed during render then it's okay: maybe you're console-logging the time while debugging (fine), or storing the impure value into a ref and only accessing it in an effect or event handler (totally ok).

This PR updates to validate that impure values are not transitively consumed during render, building on the new effects system: rather than look at instruction types, we use effects like `Capture a -> b`, `Impure a`, and `Render b` to determine how impure values are introduced and where they flow through the program. We're intentionally conservative, and do _not_ propagate impurity through MaybeCapture effects, which is used for functions we don't have signatures for. This means that things like `identity(performance.now())` drop the impurity. This feels like a good compromise since it means we have very high confidence in the errors that we report and can always add increased strictness later as our confidence increases.

An example error:

```
Error: Cannot access impure value during render

Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent).

error.invalid-impure-value-in-render-helper.ts:5:17
  3 |   const now = () => Date.now();
  4 |   const render = () => {
> 5 |     return <div>{now()}</div>;
    |                  ^^^^^ Cannot access impure value during render
  6 |   };
  7 |   return <div>{render()}</div>;
  8 | }

error.invalid-impure-value-in-render-helper.ts:3:20
  1 | // @validateNoImpureFunctionsInRender
  2 | function Component() {
> 3 |   const now = () => Date.now();
    |                     ^^^^^^^^^^ `Date.now` is an impure function.
  4 |   const render = () => {
  5 |     return <div>{now()}</div>;
  6 |   };
```

Impure values are allowed to flow into refs, meaning that we now allow `useRef(Date.now())` or `useRef(localFunctionThatReturnsMathDotRandom())` which would have errored previously. The next PR reuses this improved impurity tracking to validate ref access in render as well.

## Refs Now Treated As Impure Values in Render

Reading a ref now produces an `Impure` effect, and reading refs in render is validated using the above validation against impure values in render. The error category and message is customized for refs, we're just reusing the validation implementation. This means you get consistent results for `performance.now()` as for `ref.current`. A nice consistency win.

## Simplified writing-ref validation

Now that _reading_ a ref in render is validated using the impure values infra, I also dramatically simplified ValidateNoRefAccessInRender to focus solely on validation against _writing_ refs during render. It was harder to use the new effects infra for this since we intentionally do not record ref mutations as a `Mutate` effect. So for now, the pass switches on InstructionValue variants. We continue to support the `if (ref.current == null) { ref.current = <init> }` pattern and reasonable variants of it. We're conservative about what we consider to be a write of a ref - `foo(ref)` now assumes you're not mutating rather than the inverse.

# Takeaways

* Impure-values-in-render logic is more conservative about what it considers an error (ie to users it appears more persmissive). We follow clearly identifiable (and if we wanted traceable/explainable) paths from impure sources through to where they are rendered. We allow many more cases than before, notably `x = foo(ref)` optimistically assumes you don't read the ref. Concretely, this follows from not tracking impure values across MaybeCapture effects.
* No-writing-refs-in-render is also more conservative about what it counts as a write, appearing to users as allowing more cases. We look for very direct evidence of writing to refs, ie `ref.current = <value>` or `ref.current.property = <value>`, and allow potential writes through eg `writeToRef(ref, value)`.
Initializes CLAUDE.md and a settings file for the compiler/ directory to help use claude with the compiler. Note that some of the commands here depend on changes to snap from the next PR.
A whole bunch of changes to snap aimed at making it more usable for humans and agents. Here's the new CLI interface:

```
node dist/main.js --help
Options:
      --version         Show version number                            [boolean]
      --sync            Run compiler in main thread (instead of using worker
                        threads or subprocesses). Defaults to false.
                                                      [boolean] [default: false]
      --worker-threads  Run compiler in worker threads (instead of
                        subprocesses). Defaults to true.
                                                       [boolean] [default: true]
      --help            Show help                                      [boolean]
  -w, --watch           Run compiler in watch mode, re-running after changes
                                                                       [boolean]
  -u, --update          Update fixtures                                [boolean]
  -p, --pattern         Optional glob pattern to filter fixtures (e.g.,
                        "error.*", "use-memo")                          [string]
  -d, --debug           Enable debug logging to print HIR for each pass[boolean]
```

Key changes:
* Added abbreviations for common arguments
* No more testfilter.txt! Filtering/debugging works more like Jest, see below.
* The `--debug` flag (`-d`) controls whether to emit debug information. In watch mode, this flag sets the initial debug value, and it can be toggled by pressing the 'd' key while watching.
* The `--pattern` flag (`-p`) sets a filter pattern. In watch mode, this flag sets the initial filter. It can be changed by pressing 'p' and typing a new pattern, or pressing 'a' to switch to running all tests.
* As before, we only actually enable debugging if debug mode is enabled _and_ there is only one test selected.
@everettbu everettbu added CLA Signed React Core Team Opened by a member of the React Core Team labels Jan 16, 2026
@greptile-apps
Copy link

greptile-apps bot commented Jan 16, 2026

Greptile Summary

This PR improves the usability of the snap testing tool and enhances compiler validation logic for refs and impure functions.

Snap CLI Improvements:

  • Replaced testfilter.txt file-based filtering with command-line --pattern flag (-p)
  • Added --debug flag (-d) to control HIR debug logging
  • Implemented interactive watch mode with keyboard controls: 'd' toggles debug, 'p' enters pattern input, 'a' runs all tests
  • Debug logging now only activates when debug mode is enabled AND a single fixture is selected

Compiler Validation Enhancements:

  • Refactored ValidateNoRefAccessInRender with improved null-guard detection for ref initialization patterns like if (ref.current == null) { ref.current = value }
  • Replaced ValidateNoImpureFunctionsInRender with ValidateNoImpureValuesInRender for more comprehensive tracking of impure values through the program
  • Enhanced InferMutationAliasingEffects to add Render effects for JSX children/props and Impure effects for ref access
  • Improved function call effect propagation via Apply effects

Test Fixture Updates:

  • Many test fixtures moved from error cases to valid cases as validation became more sophisticated
  • Added new test cases for impure function validation scenarios
  • Updated error messages and expected outputs to reflect new validation logic

Confidence Score: 4/5

  • PR is safe to merge with low risk - primarily improves tooling usability and refines validation logic
  • The changes are well-structured with comprehensive test coverage (117 files changed including many test fixtures). The snap CLI improvements are straightforward UX enhancements. The validation refactors are more complex but appear carefully implemented with guard detection and effect tracking logic. Score is 4 instead of 5 due to the complexity of the validation changes which could have edge cases
  • Pay close attention to ValidateNoRefAccessInRender.ts and InferMutationAliasingEffects.ts due to the complexity of the ref validation and effect tracking logic

Important Files Changed

Filename Overview
compiler/packages/snap/src/runner.ts Improved CLI interface with new flags (-d for debug, -p for pattern), removed testfilter.txt dependency, added interactive watch mode controls
compiler/packages/snap/src/runner-watch.ts Added interactive input mode for pattern entry, debug toggle via 'd' key, pattern entry via 'p' key with keyboard handling
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoRefAccessInRender.ts Major refactor to improve ref validation logic, added guard detection for null-check patterns, better tracking of ref mutations across function calls
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoImpureValuesInRender.ts New validation pass that tracks impure values through the program, prevents impure values from being rendered (replaces ValidateNoImpureFunctionsInRender)
compiler/packages/babel-plugin-react-compiler/src/Inference/InferMutationAliasingEffects.ts Added Render effects for JSX children and props, improved ref access tracking with Impure effects, better function call effect propagation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed React Core Team Opened by a member of the React Core Team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants