## Summary
`FragmentInstance.addEventListener` and `removeEventListener` fail to
cross-match listeners when the `capture` option is passed as a
**boolean** in one call and an **options object** in the other. This
violates the [DOM Living
Standard](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener),
which states that `addEventListener(type, fn, true)` and
`addEventListener(type, fn, {capture: true})` are identical.
### Root Cause
In `ReactFiberConfigDOM.js`, the `normalizeListenerOptions` function
generates a listener key string for deduplication. The boolean branch
generates a **different format** than the object branch:
```js
// Boolean branch (old) — produces "c=1"
return `c=${opts ? '1' : '0'}`;
// Object branch — produces "c=1&o=0&p=0"
return `c=${opts.capture ? '1' : '0'}&o=${opts.once ? '1' : '0'}&p=${opts.passive ? '1' : '0'}`;
```
Because the keys differ, `indexOfEventListener` cannot match them — so
`removeEventListener('click', fn, {capture: true})` silently fails to
remove a listener registered with `addEventListener('click', fn, true)`,
and vice versa. This causes a **memory leak and event listener
accumulation** on all Fragment child DOM nodes.
### Fix
Normalize the boolean branch to produce the same full key format:
```js
// Boolean branch (fixed) — now produces "c=1&o=0&p=0" (matches object branch)
return `c=${opts ? '1' : '0'}&o=0&p=0`;
```
This makes both forms produce an identical key, matching the DOM spec
behavior.
### When Was This Introduced
This bug has been present since `FragmentInstance` event listener
tracking was first added. It became reachable in production as of
[#36026](https://github.com/facebook/react/pull/36026) which enabled
`enableFragmentRefs` + `enableFragmentRefsInstanceHandles` across all
builds (merged 3 days ago).
### Tests
Added two new regression tests to `ReactDOMFragmentRefs-test.js`:
1. `removes a capture listener registered with boolean when removed with
options object`
2. `removes a capture listener registered with options object when
removed with boolean`
Both tests were failing before this fix and pass after.
## How did you test this change?
Added two new automated tests covering both cross-form removal
directions. Existing tests continue to pass.
## Changelog
### React DOM
- **Fixed** `FragmentInstance.removeEventListener()` not removing
capture-phase listeners when the `capture` option form (boolean vs
options object) differs between `add` and `remove` calls.
## Summary
Follow-up to #36148 (which added credentialless as a recognized boolean
attribute for iframes). Adds credentialless to possibleStandardNames so
React's dev warning can suggest the correct casing when users write it
as Credentialless (or another incorrect case). Includes an SSR test
asserting the "Did you mean credentialless?" warning fires.
## Test plan
- yarn test ReactDOMComponent passes, including the new should warn
about incorrect casing on the credentialless property (ssr) case
## Summary
The `credentialless` attribute is a boolean HTML attribute for
`<iframe>` elements that loads the iframe in a new, ephemeral context
without access to the parent's credentials (cookies, client
certificates, etc.). This change adds it to all boolean attribute
switch/case lists in React DOM so it is properly handled as a boolean
(set when true, removed when false) rather than being treated as an
unknown string attribute.
Per the [Anonymous iframe spec
(WICG)](https://wicg.github.io/anonymous-iframe/):
> The credentialless attribute enables loading documents hosted by the
iframe with a new and ephemeral storage partition. It is a boolean
value. The default is false.
```
partial interface HTMLIFrameElement {
attribute boolean credentialless;
};
```
Changes:
- ReactDOMComponent.js: Added to both `setProp` and
`diffHydratedGenericElement`
- ReactFizzConfigDOM.js: Added to `pushAttribute` for server-side
rendering
- ReactDOMUnknownPropertyHook.js: Added to both validation switch/case
lists
## Test plan
- Added unit test in DOMPropertyOperations-test.js verifying
`credentialless={true}` sets the attribute to `''` and
`credentialless={false}` removes it
- All tests pass in source and www channels (590 tests each)
- Flow type checking passes (dom-node renderer)
- Prettier and lint pass
## Summary
- Adds a null check before calling
`fabricSuspendOnActiveViewTransition()` in the Fabric renderer's
`suspendOnActiveViewTransition` export
- Prevents crashes on hosts where `nativeFabricUIManager` does not yet
implement `suspendOnActiveViewTransition`
## Test plan
- Verified the change compiles correctly
- Hosts with `suspendOnActiveViewTransition` implemented continue to
work as before
- Hosts without `suspendOnActiveViewTransition` no longer crash when
view transitions are active
The `component-hook-factories` rule was removed in #35825 as part of a
feature flag cleanup, but was listed in the README as part of the manual
config example. This broke users who used a manual config (copied from
the old README) in eslint-plugin-react-hooks 7.1.0. This adds back a
deprecated no-op rule as a fix.
#35825 removed other rules (`automatic-effect-dependencies` and `fire`),
but these were for experimental features that did not ship. These were
also not referenced in the README.
## Summary
PR #36285 deleted the Paper (legacy) renderer, including the shim file
`scripts/rollup/shims/react-native/ReactNative.js`. However, the
`runtime_commit_artifacts` workflow still tries to `rm` this file after
moving build artifacts into `compiled-rn/`. Since the file no longer
exists in the build output, `rm` (without `-f`) fails and kills the
entire step.
This has caused **every run of the Commit Artifacts workflow to fail
since #36285 landed on April 16**, blocking both `builds/facebook-www`
and `builds/facebook-fbsource` branches from receiving new build
artifacts. This in turn blocks DiffTrain from syncing React changes into
Meta's internal monorepo.
The prior fix for finishedTask reentrancy solved an observed failure.
This change adds a bit of defensive bookeeping to protect against other
theoretical reentrant task finishing that might fail in simlar ways but
where we don't have a clear demonstration of the bug.
## Summary
- Wires up the native `fabricCreateViewTransitionInstance` call in
`createViewTransitionInstance` which will create a ShadowNode for old
pseudo element
- Extracts tag allocation logic into a shared `allocateTag()` function
exported from `ReactFiberConfigFabric`
- Imports `allocateTag` in `ReactFiberConfigFabricWithViewTransition`
- Reuses `allocateTag()` in `createInstance` and `createTextInstance`
instead of inline tag incrementing
- Wires up native `fabricSuspendOnActiveViewTransition` call in
`suspendOnActiveViewTransition` which suspends another view transition
when the previous one is not yet finished
## Test plan
- Existing Fabric renderer tests should continue to pass
- ViewTransition instance creation now properly allocates a tag and
calls the native module
## Summary
- Imports `startViewTransitionReadyFinished` from
`nativeFabricUIManager` in `ReactFiberConfigFabricWithViewTransition`
- Calls `fabricStartViewTransitionReadyFinished()` when the view
transition `ready` promise resolves
This is not a config function, but it's helpful to have it notify fabric
ViewTransition runtime when ready callback is done. Right now we're
testing animation kicked off from view transition event handlers, this
is signal to know when animations that belong to a transition have all
started.
## Test plan
- Existing Fabric renderer tests should continue to pass
- View transition ready callback now notifies the native module when
finished
It is possible for the fallback tasks from a Suspense boundary to
trigger an early `completeAll` call which is later repeated due to
`finishedTask` reentrancy. For node.js in particular this might be
problematic since we invoke a callback on each `completeAll` call but in
general it just isn't the right semantics since the call is running
slightly earlier than the completion of the last `finishedTask`
invocation. This change ensures that any reentrant `finishedTask` calls
(due to soft aborting fallback tasks) omit the `completeAll` call by
temporarily incrementing the total pending tasks.
## Summary
We found a bug in the logic in
https://github.com/facebook/react/pull/36253 and we realized it's very
inconvenient to iterate on the implementation when it's in this
repository, as we're forced to then synchronize it to RN to test
changes.
This moves the entire implementation to RN for simplicity and also to
simplify some clean ups in the future (like removing `top` prefixes from
native event types).
## How did you test this change?
The changes are gated. Will test e2e in RN.
## Summary
Set up the experiment to migrate event dispatching in the React Native
renderer to be based on the native EventTarget API.
Behind the `enableNativeEventTargetEventDispatching` flag, events are
dispatched through `dispatchTrustedEvent` instead of the legacy plugin
system.
Regular event handler props are NOT registered via addEventListener at
commit time. Instead, a hook on EventTarget
(`EVENT_TARGET_GET_DECLARATIVE_LISTENER_KEY`) extracts handlers from
`canonical.currentProps` at dispatch time, shifting cost from every
render to only when events fire. The hook is overridden in
ReactNativeElement to look up the prop name via a reverse mapping from
event names (built lazily from the view config registry).
Responder events bypass EventTarget entirely. `negotiateResponder` walks
the fiber tree directly (capture then bubble phase), calling handlers
from `canonical.currentProps` and checking return values inline.
Lifecycle events (`responderGrant`, `responderMove`, etc.) call handlers
directly from props and inspect return values — `onResponderGrant`
returning `true` blocks native responder,
`onResponderTerminationRequest` returning `false` refuses termination.
This eliminates all commit-time cost for responder events (no wrappers,
no addEventListener, no `responderWrappers` on canonical).
## How did you test this change?
Flow
Tested e2e in RN using Fantom tests (that will land after this).
My change in https://github.com/facebook/react/pull/35999 did not cover
all possible scenarios for emitting a warning, instead of throwing.
The instrumentation not only enables the identification for the infinite
loop via execution context checks, but also adds the check to more
lifecycle methods, like `markRootPinged` and `markRootUpdated`.
See the newly added test to understand a potential scenario. Before the
fix, the error would be thrown:
<img width="1192" height="424" alt="Screenshot 2026-04-08 at 17 21 51"
src="https://github.com/user-attachments/assets/ba8ea379-0271-4938-ae45-e37ee75e1963"
/>
With the current changes, the warning is logged with `console.error`.
PR #35951 added FB_WWW_DEV builds for eslint-plugin-react-hooks to get
www-specific feature flag values. However, the FB_WWW build uses the
full ReactFeatureFlags.www.js fork, which contains:
const dynamicFeatureFlags = require('ReactFeatureFlags');
This is a www Haste module that only exists in the www runtime. Rollup
can't tree-shake CJS require() calls (they're assumed side-effectful),
so the bare require('ReactFeatureFlags') survives in the build output
even though the eslint plugin only uses the static eprh_* exports.
When the built artifact is synced to www at
scripts/lint/eslint/rules/eslint-plugin-react-hooks/index.js, Node.js
fails with "Cannot find module 'ReactFeatureFlags'" because Haste
modules aren't available in the Node.js lint environment.
Create a dedicated fork (ReactFeatureFlags.eslint-plugin.www.js) that
exports only the static eprh_* flags with www values, without the
require('ReactFeatureFlags') dependency. Wire it up in forks.js for the
eslint-plugin-react-hooks entry point.
<!--
Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.
Before submitting a pull request, please make sure the following is
done:
1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
10. If you haven't already, complete the CLA.
Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->
Co-authored-by: Eugene Choi <eugenechoi@meta.com>
We use FB_WWW bundle to inject internal feature flag values, but need to
use NODE guard type because this is a node script -- __DEV__ is breaking
internal builds
Follow up to https://github.com/facebook/react/pull/35951
## Summary
Fixes#36101
When a component function has a destructured prop with a `NewExpression`
default value (e.g. `{ value = new Number() }`), the React Compiler
bails out during HIR construction when trying to lower the default value
via `lowerReorderableExpression`. This causes
`validateNoSetStateInEffects` to never run, silently suppressing the
`set-state-in-effect` diagnostic.
**Root cause:** `isReorderableExpression` did not have a case for
`NewExpression`, so it fell through to the `default: return false`
branch. `lowerReorderableExpression` then recorded a `Todo` error and
aborted compilation of the function before any validation passes ran.
**Fix:** Add a `NewExpression` case to `isReorderableExpression` that
mirrors the existing `CallExpression` case — the expression is safe to
reorder when the callee and all arguments are themselves reorderable
(e.g. global identifiers and literals).
## How did you test this change?
Added a new compiler fixture
`invalid-setState-in-useEffect-new-expression-default-param` that
reproduces the bug from the issue. The fixture verifies that the
`EffectSetState` diagnostic is correctly emitted for a component with a
`NewExpression` default prop value.
All 1720 compiler snapshot tests pass.
This PR adds a benchmark fixture for measuring the performance overhead
of the React Server Components (RSC) Flight rendering compared to plain
Fizz server-side rendering.
### Motivation
Performance discussions around RSC (e.g. #36143, #35125) have
highlighted the need for reproducible benchmarks that accurately measure
the cost that Flight adds on top of Fizz. This fixture provides multiple
benchmark modes that can be used to track performance improvements
across commits, compare Node vs Edge (web streams) overhead, and
identify bottlenecks in Flight serialization and deserialization.
### What it measures
The benchmark renders a dashboard app with ~25 components (16 client
components), 200 product rows with nested data (~325KB Flight payload),
and ~250 Suspense boundaries in the async variant. It compares 8 render
variants: Fizz-only and Flight+Fizz, across Node and Edge stream APIs,
with both synchronous and asynchronous apps.
### Benchmark modes
- **`yarn bench`** runs a sequential in-process benchmark with realistic
Flight script injection (tee + `TransformStream`/`Transform` buffered
injection), matching what real frameworks do when inlining the RSC
payload into the HTML response for hydration.
- **`yarn bench:bare`** runs the same benchmark without script
injection, isolating the React-internal rendering cost. This is best for
tracking changes to Flight serialization or Fizz rendering.
- **`yarn bench:server`** starts an HTTP server and uses `autocannon` to
measure real req/s at `c=1` and `c=10`. The `c=1` results provide a
clean signal for tracking React-internal changes, while `c=10` reflects
throughput under concurrent load.
- **`yarn bench:concurrent`** runs an in-process concurrent benchmark
with 50 in-flight renders via `Promise.all`, measuring throughput
without HTTP overhead.
- **`yarn bench:profile`** collects CPU profiles via the V8 inspector
and reports the top functions by self-time along with GC pause data.
- **`yarn start`** starts the HTTP server for manual browser testing.
Appending `.rsc` to any Flight URL serves the raw Flight payload.
### Key findings during development
On Node 22, the Flight+Fizz overhead compared to Fizz-only rendering is
roughly:
- **Without script injection** (`bench:bare`): ~2.2x for sync, ~1.3x for
async
- **With script injection** (`bench:server`, c=1): ~2.9x for sync, ~1.8x
for async
- **Edge vs Node** adds another ~30% for sync and ~10% for async, driven
by the stream plumbing for script injection (tee + `TransformStream`
buffering)
The async variant better represents real-world applications where server
components fetch data asynchronously. Its lower overhead reflects the
fact that Flight serialization and Fizz rendering can overlap with I/O
wait times, making the added Flight cost a smaller fraction of total
request time.
The benchmark also revealed that the Edge vs Node gap is negligible for
Fizz-only rendering (~1-2%) but grows to ~15% for Flight+Fizz sync even
without script injection. With script injection (tee + `TransformStream`
buffering), the gap roughly doubles to ~30% for sync. The async variants
show smaller gaps (~5% without, ~10% with injection).
Fixed spelling errors in comments and error messages:
- Fixed 'occured' -> 'occurred' in ReactAsyncActions-test.js
- Fixed 'teh' -> 'the' in ReactFiberConfigDOM.js
- Fixed 'occured' -> 'occurred' in ErrorBoundary.js
- Fixed 'accomodate' -> 'accommodate' in InferMutationAliasingEffects.ts
<!--
Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.
Before submitting a pull request, please make sure the following is
done:
1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
10. If you haven't already, complete the CLA.
Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->
## Summary
<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->
## How did you test this change?
<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
If you leave this empty, your PR will very likely be closed.
-->
Hi! While reviewing the React Compiler documentation, I noticed a few
minor issues in DESIGN_GOALS.md:
- Fixed a typo: `outweight` → `outweigh` in the Non-Goals section.
- Updated all instances of `ie` to the standard `i.e.` for better
consistency and clarity throughout the document.
Happy to contribute!
<!--
Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.
Before submitting a pull request, please make sure the following is
done:
1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
10. If you haven't already, complete the CLA.
Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->
## Summary
Fixed a typo (outweight -> outweigh) and standardized abbreviation usage
(ie -> i.e.) in the DESIGN_GOALS.md file for the React Compiler
documentation. This improves the overall professionalism and readability
of the document.
## How did you test this change?
This is a documentation-only change. I verified the formatting and
consistency of the edits.
Compiler config parsing is currently done with new Function(...) which
is a XSS vulnerability. Replacing this with json parsing for safety
reasons.
Almost all compiler options (except for moduleTypeProvider) are json
compatible, so this isn't a big change to capabilities. Previously
created playground URLs with non-default configs may not be compatible
with this change, but we should be able to get the correct config
manually (by reading the JS version)
## Summary
When a context value changes above a Suspense boundary that is showing
its fallback, context consumers inside the fallback do not re-render —
they display stale values.
`propagateContextChanges`, upon encountering a suspended Suspense
boundary, marks the boundary for retry but stops traversing into its
children entirely (`nextFiber = null`). This skips both the hidden
primary subtree (intentional — those fibers may not exist) and the
visible fallback subtree (a bug — those fibers are committed and visible
to the user).
The fix skips the primary OffscreenComponent and continues traversal
into the FallbackFragment, so fallback context consumers are found and
marked for re-render.
In practice this often goes unnoticed because it's uncommon to read
context inside a Suspense fallback, and when some other update (like a
prop change) flows into the fallback it sidesteps the propagation path
entirely. React Compiler makes the bug more likely to surface since it
memoizes more aggressively, reducing the chance of an incidental
re-render masking the stale value.
## Test plan
- Added regression test `'context change propagates to Suspense fallback
(memo boundary)'` in `ReactContextPropagation-test.js`
- Verified the test fails without the fix and passes with it
- All existing context propagation, Suspense, memo, and hooks tests pass
<!--
Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.
Before submitting a pull request, please make sure the following is
done:
1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
10. If you haven't already, complete the CLA.
Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->
## Summary
This PR fixes a few small spelling errors in comments across the
codebase (`teh`→`the`, `occuring`→`occurring`, `occured`→`occurred`). No
behavior changes.
<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->
## How did you test this change?
<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
If you leave this empty, your PR will very likely be closed.
-->
This is a comments-only change. I verified the diff is limited to
comment text and does not affect logic or runtime behavior.
<!--
Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.
Before submitting a pull request, please make sure the following is
done:
1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
10. If you haven't already, complete the CLA.
Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->
## Summary
<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->
I just fixed typos as followings.
- `succesful` → `successful`
- `becuase` → `because`
- `enought` → `enough`
- `defualt` → `default`
## How did you test this change?
<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
If you leave this empty, your PR will very likely be closed.
-->
This PR only includes test case description, dummy strings for test, and
comments updates, so it has no impact on runtime behavior.
Therefore, I manually reviewed changed texts to ensure correctness.
Fixed spelling errors:
- Fixed 'explicitlyu' -> 'explicitly' in compiler/CLAUDE.md
- Fixed 'intialized' -> 'initialized' in InferReactiveScopeVariables.ts
(comment)
- Fixed 'intialized' -> 'initialized' in InferMutationAliasingEffects.ts
(error message)
<!--
Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.
Before submitting a pull request, please make sure the following is
done:
1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
10. If you haven't already, complete the CLA.
Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->
## Summary
<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->
## How did you test this change?
<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
If you leave this empty, your PR will very likely be closed.
-->
Fixed spelling error in comment:
- Fixed 'accomodate' -> 'accommodate' in InferMutationAliasingEffects.ts
<!--
Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.
Before submitting a pull request, please make sure the following is
done:
1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
10. If you haven't already, complete the CLA.
Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->
## Summary
<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->
## How did you test this change?
<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
If you leave this empty, your PR will very likely be closed.
-->
We're currently hardcoding experimental options to
`eslint-plugin-react-hooks`. This blocks the release on features that
might not be ready.
This PR extends the ReactFeatureFlag infra to support flags for
`eslint-plugin-react-hooks`. An alternative would be to create a
separate flag system for build tools, but for now we have a small number
of these and reusing existing infra seems like the simplest approach.
I ran a full `yarn build` and checked the output resolved the flag
values as expected:
_build/oss-stable-semver/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js_
```js
var eprh_enableUseKeyedStateCompilerLint = false;
var eprh_enableVerboseNoSetStateInEffectCompilerLint = false;
var eprh_enableExhaustiveEffectDependenciesCompilerLint = 'off';
```
_build/facebook-www/ESLintPluginReactHooks-dev.classic.js_
```js
var eprh_enableUseKeyedStateCompilerLint = true;
var eprh_enableVerboseNoSetStateInEffectCompilerLint = true;
var eprh_enableExhaustiveEffectDependenciesCompilerLint = 'extra-only';
```
---------
Co-authored-by: lauren <lauren@anysphere.co>
<!--
Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.
Before submitting a pull request, please make sure the following is
done:
1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
10. If you haven't already, complete the CLA.
Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->
## Summary
<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->
So in this PR the typo mistakes in the docs are corrected such as the
1. **Ie** it should be **"i.e"**.
2. **errros** should be the **"errors"**.
3. **consdier** should be the **"consider"**.
4. **CreatFrom** should be **"CreateForm"**.
## How did you test this change?
<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
If you leave this empty, your PR will very likely be closed.
-->
I verified the fixes by reviewing the updated files locally to ensure
the corrected terms appear consistently and accurately in the
documentation.
---------
Co-authored-by: Yummy_Bacon5 <68166338+YummyBacon5@users.noreply.github.com>
## Summary
Enables Basic View Transition support for React Native Fabric renderer.
**Implemented:**
- Added FabricUIManager bindings for view transition methods:
`applyViewTransitionName`, `startViewTransition`
- Implemented `startViewTransition` with proper callback orchestration
(mutation → layout → afterMutation → spawnedWork → passive)
- Added fallback behavior that flushes work synchronously when Fabric's
`startViewTransition` returns null (e.g., when the ViewTransition
ReactNativeFeatureFlag is not enabled)
- Added Flow type declarations for new FabricUIManager methods
- Stubbed with `__DEV__` warnings for all the other view transition
config functions that are not yet implemented
This allows React Native apps using Fabric to leverage the View
Transition API for coordinated animations during state transitions, with
graceful degradation when the native side doesn't support it.
Below are diagrams of proposed architecture in fabric, and observation
of what/when config functions get called during a basic shared
transition example
<img width="2290" height="1529" alt="Untitled-2026-03-19-1240"
src="https://github.com/user-attachments/assets/192c9169-bc25-449c-a33b-dfec67179e7f"
/>
## How did you test this change?
- [x] `yarn flow fabric` - Flow type checks pass
- [x] `yarn lint` - Lint checks pass
- [x] Manually tested in Android catalyst app with
`enableViewTransition` and `enableViewTransitionForPersistenceMode `in
`ReactFeatureFlags.test-renderer.native-fb.js` and View Transition
enabled via ReactNativeFeatureFlag
- [x] Verified in the minified `ReactFabric-dev.fb.js` that the 'shim'
config functions are not included
- [x] Verified fallback behavior logs warning in `__DEV__` and flushes
work synchronously when ViewTransition flag isn't enabled in Fabric
The `enableInfiniteRenderLoopDetection` feature flag is currently
disabled everywhere. When attempted to roll out this at Meta, we've
observed multiple false-positives, where counter-based approach would
interrupt the render that would've resolved at some later iteration.
This change gates the scenarios that are only discovered with the
instrumentation behind `enableInfiniteRenderLoopDetection` flag to warn
about potential infinite loop, instead of throwing an error and hitting
an error boundary. The main reason is to see if we can a signal on which
possible area of scenarios this new approach to infinite loops covers.
The gist of the approach is to ensure that we are still throwing error
and breaking the infinite loop, if we were doing this without
`enableInfiniteRenderLoopDetection` feature flag enabled.
This will log multiple errors if there is an infinite loop, but this
should be fine, and it also aligns with the pattern for warnings about
passive effects infinite loop.
I've validated that tests in `ReactUpdates-test.js` are passing
independently whether the feature flag is enabled or not.
I found two focus bugs when working on documentation for Fragment Refs.
1) If an element delegates focus handling, it will return false from
setFocusIfFocusable even though a focus event has occured on a different
element. The fix for this is a document level event listener rather than
only listening on the current element.
For example, if you have a form with multiple nested label>inputs.
Calling focus on the label will focus its input but not fire an event on
the label. setFocusIfFocusable returns false and you end up continuing
to attempt focus down the form tree.
2) If an element is already focused, setFocusIfFocusable will return
false. The fix for this is checking the document's activeElement with an
early return.
In the same form example, if the first input is already focused and you
call fragmentInstance.focus() at the form level, the second input would
end up getting focused since the focus event on the first is not
triggered.
When `requireModule` triggers a reentrant `readChunk` on the same module
chunk, the reentrant call can fail and set `chunk.reason` to an error.
After the outer `requireModule` succeeds, the chunk transitions to
initialized but retains the stale error as `reason`.
When the Flight response stream later closes, it iterates all chunks and
expects `reason` on initialized chunks to be a `FlightStreamController`.
Since the stale `reason` is an `Error` object instead, calling
`chunk.reason.error()` crashes with `TypeError: chunk.reason.error is
not a function`.
The reentrancy can occur when module evaluation synchronously triggers
`readChunk` on the same chunk — for example, when code called during
evaluation tries to resolve the client reference for the module that is
currently being initialized. In Fizz SSR, `captureOwnerStack()` can
trigger this because it constructs component stacks that resolve lazy
client references via `readChunk`. The reentrant `requireModule` call
returns the module's namespace object, but since the module is still
being evaluated, accessing the export binding throws a TDZ (Temporal
Dead Zone) `ReferenceError`. This sets the chunk to the errored state,
and the `ReferenceError` becomes the stale `chunk.reason` after the
outer call succeeds.
This scenario is triggered in Next.js when a client module calls an
instrumented API like `Math.random()` in module scope, which
synchronously invokes `captureOwnerStack()`.
Bumps [qs](https://github.com/ljharb/qs) from 6.4.0 to 6.4.1.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ljharb/qs/blob/main/CHANGELOG.md">qs's
changelog</a>.</em></p>
<blockquote>
<h2><strong>6.4.1</strong></h2>
<ul>
<li>[Fix] <code>parse</code>: ignore <code>__proto__</code> keys (<a
href="https://redirect.github.com/ljharb/qs/issues/428">#428</a>)</li>
<li>[Fix] fix for an impossible situation: when the formatter is called
with a non-string value</li>
<li>[Fix] use <code>safer-buffer</code> instead of <code>Buffer</code>
constructor</li>
<li>[Fix] <code>utils.merge</code>: avoid a crash with a null target and
an array source</li>
<li>[Fix] <code>utils.merge</code>: avoid a crash with a null target and
a truthy non-array source</li>
<li>[Fix] <code>stringify</code>: fix a crash with
<code>strictNullHandling</code> and a custom
<code>filter</code>/<code>serializeDate</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/279">#279</a>)</li>
<li>[Fix] <code>utils</code>: <code>merge</code>: fix crash when
<code>source</code> is a truthy primitive & no options are
provided</li>
<li>[Fix] when <code>parseArrays</code> is false, properly handle keys
ending in <code>[]</code></li>
<li>[Robustness] <code>stringify</code>: avoid relying on a global
<code>undefined</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/427">#427</a>)</li>
<li>[Refactor] use cached <code>Array.isArray</code></li>
<li>[Refactor] <code>stringify</code>: Avoid arr = arr.concat(...), push
to the existing instance (<a
href="https://redirect.github.com/ljharb/qs/issues/269">#269</a>)</li>
<li>[readme] remove travis badge; add github actions/codecov badges;
update URLs</li>
<li>[Docs] Clarify the need for "arrayLimit" option</li>
<li>[meta] fix README.md (<a
href="https://redirect.github.com/ljharb/qs/issues/399">#399</a>)</li>
<li>[meta] Clean up license text so it’s properly detected as
BSD-3-Clause</li>
<li>[meta] add FUNDING.yml</li>
<li>[actions] backport actions from main</li>
<li>[Tests] remove nonexistent tape option</li>
<li>[Dev Deps] backport from main</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="486aa46547"><code>486aa46</code></a>
v6.4.1</li>
<li><a
href="727ef5d346"><code>727ef5d</code></a>
[Fix] <code>parse</code>: ignore <code>__proto__</code> keys (<a
href="https://redirect.github.com/ljharb/qs/issues/428">#428</a>)</li>
<li><a
href="cd1874eb17"><code>cd1874e</code></a>
[Robustness] <code>stringify</code>: avoid relying on a global
<code>undefined</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/427">#427</a>)</li>
<li><a
href="45e987c603"><code>45e987c</code></a>
[readme] remove travis badge; add github actions/codecov badges; update
URLs</li>
<li><a
href="90a3bced51"><code>90a3bce</code></a>
[meta] fix README.md (<a
href="https://redirect.github.com/ljharb/qs/issues/399">#399</a>)</li>
<li><a
href="9566d25019"><code>9566d25</code></a>
[Fix] fix for an impossible situation: when the formatter is called with
a no...</li>
<li><a
href="74227ef022"><code>74227ef</code></a>
Clean up license text so it’s properly detected as BSD-3-Clause</li>
<li><a
href="35dfb227e2"><code>35dfb22</code></a>
[actions] backport actions from main</li>
<li><a
href="7d4670fca6"><code>7d4670f</code></a>
[Dev Deps] backport from main</li>
<li><a
href="0485440902"><code>0485440</code></a>
[Fix] use <code>safer-buffer</code> instead of <code>Buffer</code>
constructor</li>
<li>Additional commits viewable in <a
href="https://github.com/ljharb/qs/compare/v6.4.0...v6.4.1">compare
view</a></li>
</ul>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)
Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/facebook/react/network/alerts).
</details>
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Bumps [qs](https://github.com/ljharb/qs) from 6.4.0 to 6.4.1.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ljharb/qs/blob/main/CHANGELOG.md">qs's
changelog</a>.</em></p>
<blockquote>
<h2><strong>6.4.1</strong></h2>
<ul>
<li>[Fix] <code>parse</code>: ignore <code>__proto__</code> keys (<a
href="https://redirect.github.com/ljharb/qs/issues/428">#428</a>)</li>
<li>[Fix] fix for an impossible situation: when the formatter is called
with a non-string value</li>
<li>[Fix] use <code>safer-buffer</code> instead of <code>Buffer</code>
constructor</li>
<li>[Fix] <code>utils.merge</code>: avoid a crash with a null target and
an array source</li>
<li>[Fix] <code>utils.merge</code>: avoid a crash with a null target and
a truthy non-array source</li>
<li>[Fix] <code>stringify</code>: fix a crash with
<code>strictNullHandling</code> and a custom
<code>filter</code>/<code>serializeDate</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/279">#279</a>)</li>
<li>[Fix] <code>utils</code>: <code>merge</code>: fix crash when
<code>source</code> is a truthy primitive & no options are
provided</li>
<li>[Fix] when <code>parseArrays</code> is false, properly handle keys
ending in <code>[]</code></li>
<li>[Robustness] <code>stringify</code>: avoid relying on a global
<code>undefined</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/427">#427</a>)</li>
<li>[Refactor] use cached <code>Array.isArray</code></li>
<li>[Refactor] <code>stringify</code>: Avoid arr = arr.concat(...), push
to the existing instance (<a
href="https://redirect.github.com/ljharb/qs/issues/269">#269</a>)</li>
<li>[readme] remove travis badge; add github actions/codecov badges;
update URLs</li>
<li>[Docs] Clarify the need for "arrayLimit" option</li>
<li>[meta] fix README.md (<a
href="https://redirect.github.com/ljharb/qs/issues/399">#399</a>)</li>
<li>[meta] Clean up license text so it’s properly detected as
BSD-3-Clause</li>
<li>[meta] add FUNDING.yml</li>
<li>[actions] backport actions from main</li>
<li>[Tests] remove nonexistent tape option</li>
<li>[Dev Deps] backport from main</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="486aa46547"><code>486aa46</code></a>
v6.4.1</li>
<li><a
href="727ef5d346"><code>727ef5d</code></a>
[Fix] <code>parse</code>: ignore <code>__proto__</code> keys (<a
href="https://redirect.github.com/ljharb/qs/issues/428">#428</a>)</li>
<li><a
href="cd1874eb17"><code>cd1874e</code></a>
[Robustness] <code>stringify</code>: avoid relying on a global
<code>undefined</code> (<a
href="https://redirect.github.com/ljharb/qs/issues/427">#427</a>)</li>
<li><a
href="45e987c603"><code>45e987c</code></a>
[readme] remove travis badge; add github actions/codecov badges; update
URLs</li>
<li><a
href="90a3bced51"><code>90a3bce</code></a>
[meta] fix README.md (<a
href="https://redirect.github.com/ljharb/qs/issues/399">#399</a>)</li>
<li><a
href="9566d25019"><code>9566d25</code></a>
[Fix] fix for an impossible situation: when the formatter is called with
a no...</li>
<li><a
href="74227ef022"><code>74227ef</code></a>
Clean up license text so it’s properly detected as BSD-3-Clause</li>
<li><a
href="35dfb227e2"><code>35dfb22</code></a>
[actions] backport actions from main</li>
<li><a
href="7d4670fca6"><code>7d4670f</code></a>
[Dev Deps] backport from main</li>
<li><a
href="0485440902"><code>0485440</code></a>
[Fix] use <code>safer-buffer</code> instead of <code>Buffer</code>
constructor</li>
<li>Additional commits viewable in <a
href="https://github.com/ljharb/qs/compare/v6.4.0...v6.4.1">compare
view</a></li>
</ul>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)
Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/facebook/react/network/alerts).
</details>
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Bumps [jws](https://github.com/brianloveswords/node-jws) from 3.2.2 to
3.2.3.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/brianloveswords/node-jws/releases">jws's
releases</a>.</em></p>
<blockquote>
<h2>v3.2.3</h2>
<h3>Changed</h3>
<ul>
<li>Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now
require
that a non empty secret is provided (via opts.secret, opts.privateKey or
opts.key)
when using HMAC algorithms.</li>
<li>Upgrading JWA version to 1.4.2, addressing a compatibility issue for
Node >= 25.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/auth0/node-jws/blob/master/CHANGELOG.md">jws's
changelog</a>.</em></p>
<blockquote>
<h2>[3.2.3]</h2>
<h3>Changed</h3>
<ul>
<li>Fix advisory GHSA-869p-cjfg-cm3x: createSign and createVerify now
require
that a non empty secret is provided (via opts.secret, opts.privateKey or
opts.key)
when using HMAC algorithms.</li>
<li>Upgrading JWA version to 1.4.2, adressing a compatibility issue for
Node >= 25.</li>
</ul>
<h2>[3.0.0]</h2>
<h3>Changed</h3>
<ul>
<li><strong>BREAKING</strong>: <code>jwt.verify</code> now requires an
<code>algorithm</code> parameter, and
<code>jws.createVerify</code> requires an <code>algorithm</code> option.
The <code>"alg"</code> field
signature headers is ignored. This mitigates a critical security flaw
in the library which would allow an attacker to generate signatures with
arbitrary contents that would be accepted by <code>jwt.verify</code>.
See
<a
href="https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/">https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/</a>
for details.</li>
</ul>
<h2><a
href="https://github.com/brianloveswords/node-jws/compare/v1.0.1...v2.0.0">2.0.0</a>
- 2015-01-30</h2>
<h3>Changed</h3>
<ul>
<li>
<p><strong>BREAKING</strong>: Default payload encoding changed from
<code>binary</code> to
<code>utf8</code>. <code>utf8</code> is a is a more sensible default
than <code>binary</code> because
many payloads, as far as I can tell, will contain user-facing
strings that could be in any language. (<!-- raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/6b6de48">6b6de48</a><!--
raw HTML omitted -->)</p>
</li>
<li>
<p>Code reorganization, thanks <a
href="https://github.com/fearphage"><code>@fearphage</code></a>! (<!--
raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/7880050">7880050</a><!--
raw HTML omitted -->)</p>
</li>
</ul>
<h3>Added</h3>
<ul>
<li>Option in all relevant methods for <code>encoding</code>. For those
few users
that might be depending on a <code>binary</code> encoding of the
messages, this
is for them. (<!-- raw HTML omitted --><a
href="https://github.com/brianloveswords/node-jws/commit/6b6de48">6b6de48</a><!--
raw HTML omitted -->)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="4f6e73f24d"><code>4f6e73f</code></a>
Merge commit from fork</li>
<li><a
href="bd0fea57f3"><code>bd0fea5</code></a>
version 3.2.3</li>
<li><a
href="7c3b4b4110"><code>7c3b4b4</code></a>
Enhance tests for HMAC streaming sign and verify</li>
<li><a
href="a9b8ed999d"><code>a9b8ed9</code></a>
Improve secretOrKey initialization in VerifyStream</li>
<li><a
href="6707fde62c"><code>6707fde</code></a>
Improve secret handling in SignStream</li>
<li>See full diff in <a
href="https://github.com/brianloveswords/node-jws/compare/v3.2.2...v3.2.3">compare
view</a></li>
</ul>
</details>
<details>
<summary>Maintainer changes</summary>
<p>This version was pushed to npm by <a
href="https://www.npmjs.com/~julien.wollscheid">julien.wollscheid</a>, a
new releaser for jws since your current version.</p>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)
Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/facebook/react/network/alerts).
</details>
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
https://github.com/facebook/react/pull/34935 Introduced
`unstable_reactFragments` handle on DOM nodes to enable caching of
Observers.
This has been tested in production and is stable so it can be rolled out
with the Fragment Refs feature.
## Summary
This defines the same fiber configuration for RN as used in DOM, so we
can expose event timing information in the React scheduler tracks in
performance traces.
This was unblocked by #35913 and #35912.
## How did you test this change?
Manually compiled the renderer and tested e2e in FB infra:
<img width="1217" height="161" alt="Screenshot 2026-03-03 at 10 10 44"
src="https://github.com/user-attachments/assets/6ca1512e-dcaf-49cf-8da9-1c6ae554733a"
/>
I am in a process of splitting down the renderer implementation into
smaller units of logic that can be reused. This change is about
extracting pure functions only.
With the recent changes to make the compiler fault tolerant and always
continue through all passes, we can now sometimes report duplicative
errors. Specifically, when `ValidateExhaustiveDependencies` finds
incorrect deps for a useMemo/useCallback call,
`ValidatePreservedManualMemoization` will generally also error for the
same block, producing duplicate errors. The exhaustive deps error is
strictly more informative, so if we've already reported the earlier
error we don't need the later one.
This adds a `hasInvalidDeps` flag to StartMemoize that is set when
ValidateExhaustiveDependencies produces a diagnostic.
ValidatePreservedManualMemoization then skips validation for memo blocks
with this flag set.
## Summary
This fixes the semantics of the `timeStamp` property of events in React
Native.
Currently, most events just assign `Date.now()` (at the time of creating
the event object in JavaScript) as the `timeStamp` property. This is a
divergence with Web and most native platforms, that use a monotonic
timestamp for the value (on Web, the same timestamp provided by
`performance.now()`).
Additionally, many native events specify a timestamp in the event data
object as `timestamp` and gets ignored by the logic in JS as it only
looks at properties named `timeStamp` specifically (camel case).
This PR fixes both issues by:
1. Using `performance.now()` instead of `Date.now()` by default (if
available).
2. Checking for a `timestamp` property before falling back to the
default (apart from `timeStamp`).
## How did you test this change?
Added unit tests for verify the new behavior.
## Summary
This flag enables React's integration with the browser [Trusted Types
API](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API).
The Trusted Types API is a browser security feature that helps prevent
DOM-based XSS attacks. When a site enables Trusted Types enforcement via
`Content-Security-Policy: require-trusted-types-for 'script'`, the
browser requires that values passed to DOM injection sinks (like
`innerHTML`) are typed objects (`TrustedHTML`, `TrustedScript`,
`TrustedScriptURL`) created through developer-defined sanitization
policies, rather than raw strings.
### What changed
Previously, React always coerced values to strings (via `'' + value`)
before passing them to DOM APIs like `setAttribute` and `innerHTML`.
This broke Trusted Types because it converted typed objects into plain
strings, which the browser would then reject under Trusted Types
enforcement.
React now passes values directly to DOM APIs without string coercion,
preserving Trusted Types objects so the browser can validate them. This
applies to `dangerouslySetInnerHTML`, all HTML and SVG attributes, and
URL attributes (`href`, `action`, etc).
### Before (broken)
Using Trusted Types with something like`dangerouslySetInnerHTML` would
throw:
```js
const sanitizer = trustedTypes.createPolicy('sanitizer', {
createHTML: (input) => DOMPurify.sanitize(input),
});
function Comment({text}) {
const clean = sanitizer.createHTML(text);
// clean is a TrustedHTML object, but React would call '' + clean,
// converting it back to a plain string before setting innerHTML.
// Under Trusted Types enforcement, the browser rejects the string:
//
// TypeError: Failed to set 'innerHTML' on 'Element':
// This document requires 'TrustedHTML' assignment.
return <div dangerouslySetInnerHTML={{__html: clean}} />;
}
```
### After (works)
React now passes the TrustedHTML object directly to the DOM without
stringifying it:
```js
const policy = trustedTypes.createPolicy('sanitizer', {
createHTML: (input) => DOMPurify.sanitize(input),
});
function Comment({text}) {
// TrustedHTML objects are passed directly to innerHTML
return <div dangerouslySetInnerHTML={{__html: policy.createHTML(text)}} />;
}
function UserProfile({bio}) {
// String attribute values also preserve Trusted Types objects
return <div data-bio={policy.createHTML(bio)} />;
}
```
## Non-breaking change
- Sites using Trusted Types: React no longer breaks Trusted Types enforcement. TrustedHTML and TrustedScriptURL objects passed through React props are forwarded to the DOM without being stringified.
- Sites not using Trusted Types: No behavior change. DOM APIs accept both strings and Trusted Types objects, so removing the explicit string coercion is functionally identical.
If a function is known to freeze its inputs, and captures refs, then we
can safely assume those refs are not mutated during render.
An example is React Native's PanResponder, which is designed for use in
interaction handling. Calling `PanResponder.create()` creates an object
that shouldn't be interacted with at render time, so we can treat it as
freezing its arguments, returning a frozen value, and not accessing any
refs in the callbacks passed to it. ValidateNoRefAccessInRender is
updated accordingly - if we see a Freeze <place> and ImmutableCapture
<place> for the same place in the same instruction, we know that it's
not being mutated.
Note that this is a pretty targeted fix. One weakness is that we may not
always emit a Freeze effect if a value is already frozen, which could
cause this optimization not to kick in. The worst case there is that
you'd just get a ref access in render error though, not miscompilation.
And we could always choose to always emit Freeze effects, even for
frozen values, just to retain the information for validations like this.
## Summary
This enables routing the React Dev Tools through a remote server by
being able to specify host, port, and path for the client to connect to.
Basically allowing the React Dev Tools server to have the client connect
elsewhere.
This setups a `clientOptions` which can be set up through environment
variables when starting the React Dev Tools server.
This change shouldn't affect the traditional usage for React Dev Tools.
EDIT: the additional change was moved to another PR
## How did you test this change?
Run React DevTools with
```
$ REACT_DEVTOOLS_CLIENT_HOST=<MY_HOST> REACT_DEVTOOLS_CLIENT_PORT=443 REACT_DEVTOOLS_CLIENT_USE_HTTPS=true REACT_DEVTOOLS_PATH=/__react_devtools__/ yarn start
```
Confirm that my application connects to the local React Dev Tools
server/instance/electron app through my remote server.
## Summary
For apps that use AMD, we need to actually `require()` the
ReactDevToolsBackend and load it from the AMD module cache. This adds a
check for the case where the `ReactDevToolsBackend` isn't defined
globally, and so we load it with `require()`.
## How did you test this change?
Tested through https://github.com/facebook/react/pull/35886
Add concise fault tolerance documentation to CLAUDE.md and the passes
README covering error accumulation, tryRecord wrapping, and the
distinction between validation vs infrastructure passes. Remove the
detailed planning document now that the work is complete.
Fix the transformFire early-exit in Pipeline.ts to only trigger on new
errors from transformFire itself, not pre-existing errors from earlier
passes. The previous `env.hasErrors()` check was too broad — it would
early-exit on validation errors that existed before transformFire ran.
Also add missing blank line in CodegenReactiveFunction.ts Context class,
and fix formatting in ValidateMemoizedEffectDependencies.ts.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35884).
* #35888
* __->__ #35884
Rename `state: Environment` to `env: Environment` in
ValidateMemoizedEffectDependencies visitor methods, and
`errorState: Environment` to `env: Environment` in
ValidatePreservedManualMemoization's validateInferredDep.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35883).
* #35888
* #35884
* __->__ #35883
Removes unnecessary indirection in 17 compiler passes that previously
accumulated errors in a local `CompilerError` instance before flushing
them to `env.recordErrors()` at the end of each pass. Errors are now
emitted directly via `env.recordError()` as they're discovered.
For passes with recursive error-detection patterns
(ValidateNoRefAccessInRender,
ValidateNoSetStateInRender), the internal accumulator is kept but
flushed
via individual `recordError()` calls. For InferMutationAliasingRanges,
a `shouldRecordErrors` flag preserves the conditional suppression logic.
For TransformFire, the throw-based error propagation is replaced with
direct recording plus an early-exit check in Pipeline.ts.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35882).
* #35888
* #35884
* #35883
* __->__ #35882
Remove `tryRecord()` from the compilation pipeline now that all passes
record
errors directly via `env.recordError()` / `env.recordErrors()`. A single
catch-all try/catch in Program.ts provides the safety net for any pass
that
incorrectly throws instead of recording.
Key changes:
- Remove all ~64 `env.tryRecord()` wrappers in Pipeline.ts
- Delete `tryRecord()` method from Environment.ts
- Add `CompileUnexpectedThrow` logger event so thrown errors are
detectable
- Log `CompileUnexpectedThrow` in Program.ts catch-all for non-invariant
throws
- Fail snap tests on `CompileUnexpectedThrow` to surface pass bugs in
dev
- Convert throwTodo/throwDiagnostic calls in HIRBuilder (fbt, this),
CodegenReactiveFunction (for-in/for-of), and BuildReactiveFunction to
record errors or use invariants as appropriate
- Remove try/catch from BuildHIR's lower() since inner throws are now
recorded
- CollectOptionalChainDependencies: return null instead of throwing on
unsupported optional chain patterns (graceful optimization skip)
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35881).
* #35888
* #35884
* #35883
* #35882
* __->__ #35881
Add test fixture demonstrating fault tolerance: the compiler now reports
both a mutation error and a ref access error in the same function, where
previously only one would be reported before bailing out.
Update plan doc to mark all phases as complete.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35877).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* __->__ #35877
- Change runWithEnvironment/run/compileFn to return
Result<CodegenFunction, CompilerError>
- Wrap all pipeline passes in env.tryRecord() to catch and record
CompilerErrors
- Record inference pass errors via env.recordErrors() instead of
throwing
- Handle codegen Result explicitly, returning Err on failure
- Add final error check: return Err(env.aggregateErrors()) if any errors
accumulated
- Update tryCompileFunction and retryCompileFunction in Program.ts to
handle Result
- Keep lint-only passes using env.logErrors() (non-blocking)
- Update 52 test fixture expectations that now report additional errors
This is the core integration that enables fault tolerance: errors are
caught,
recorded, and the pipeline continues to discover more errors.
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35874).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* #35877
* #35876
* #35875
* __->__ #35874
Add error accumulation methods to the Environment class:
- #errors field to accumulate CompilerErrors across passes
- recordError() to record a single diagnostic (throws if Invariant)
- recordErrors() to record all diagnostics from a CompilerError
- hasErrors() to check if any errors have been recorded
- aggregateErrors() to retrieve the accumulated CompilerError
- tryRecord() to wrap callbacks and catch CompilerErrors
---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35873).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* #35877
* #35876
* #35875
* #35874
* __->__ #35873
Remove dead code left behind after the removal of retryCompileFunction,
enableFire, and inferEffectDependencies:
- Delete ValidateNoUntransformedReferences.ts (always a no-op)
- Remove CompileProgramMetadata type and retryErrors from ProgramContext
- Remove 'client-no-memo' output mode
- Change compileProgram return type from CompileProgramMetadata | null
to void
When a Suspense boundary suspends during initial mount, the primary
children's fibers are discarded because there is no current tree to
preserve them. If the suspended promise never resolves, the only way to
retry is something external like a context change. However, lazy context
propagation could not find the consumer fibers — they no longer exist in
the tree — so the Suspense boundary was never marked for retry and
remained stuck in fallback state indefinitely.
The fix teaches context propagation to conservatively mark suspended
Suspense boundaries for retry when a parent context changes, even when
the consumer fibers can't be found. This matches the existing
conservative approach used for dehydrated (SSR) Suspense boundaries.
2026-02-20 22:03:11 -05:00
332 changed files with 13518 additions and 7895 deletions
- name:Insert @headers into eslint plugin and react-refresh
run:|
sed -i -e 's/ LICENSE file in the root directory of this source tree./ LICENSE file in the root directory of this source tree.\n *\n * @noformat\n * @nolint\n * @lightSyntaxTransform\n * @preventMunge\n * @oncall react_core/' \
This repository uses Sapling (`sl`) for version control. Sapling is similar to Mercurial: there is not staging area, but new/deleted files must be explicitlyu added/removed.
This repository uses Sapling (`sl`) for version control. Sapling is similar to Mercurial: there is not staging area, but new/deleted files must be explicitly added/removed.
```bash
# Check status
@@ -229,20 +243,19 @@ Would enable the `enableJsxOutlining` feature and disable the `enableNameAnonymo
3. Look for `Impure`, `Render`, `Capture` effects on instructions
4. Check the pass ordering in Pipeline.ts to understand when effects are populated vs validated
## Error Handling for Unsupported Features
## Error Handling and Fault Tolerance
When the compiler encounters an unsupported but known pattern, use `CompilerError.throwTodo()` instead of `CompilerError.invariant()`. Todo errors cause graceful bailouts in production; Invariant errors are hard failures indicating unexpected/invalid states.
The compiler is fault-tolerant: it runs all passes and accumulates errors on the `Environment` rather than throwing on the first error. This lets users see all compilation errors at once.
```typescript
// Unsupported but expected pattern - graceful bailout
CompilerError.throwTodo({
reason:`Support [description of unsupported feature]`,
loc: terminal.loc,
});
**Recording errors** — Passes record errors via `env.recordError(diagnostic)`. Errors are accumulated on `Environment.#errors` and checked at the end of the pipeline via `env.hasErrors()` / `env.aggregateErrors()`.
// Invariant is for truly unexpected/invalid states - hard failure
CompilerError.invariant(false,{
reason:`Unexpected [thing]`,
loc: terminal.loc,
});
```
**`tryRecord()` wrapper** — In Pipeline.ts, validation passes are wrapped in `env.tryRecord(() => pass(hir))` which catches thrown `CompilerError`s (non-invariant) and records them. Infrastructure/transformation passes are NOT wrapped in `tryRecord()` because later passes depend on their output being structurally valid.
**Error categories:**
-`CompilerError.throwTodo()` — Unsupported but known pattern. Graceful bailout. Can be caught by `tryRecord()`.
-`CompilerError.invariant()` — Truly unexpected/invalid state. Always throws immediately, never caught by `tryRecord()`.
@@ -8,7 +8,7 @@ The idea of React Compiler is to allow developers to use React's familiar declar
* Bound the amount of re-rendering that happens on updates to ensure that apps have predictably fast performance by default.
* Keep startup time neutral with pre-React Compiler performance. Notably, this means holding code size increases and memoization overhead low enough to not impact startup.
* Retain React's familiar declarative, component-oriented programming model. Ie, the solution should not fundamentally change how developers think about writing React, and should generally _remove_ concepts (the need to use React.memo(), useMemo(), and useCallback()) rather than introduce new concepts.
* Retain React's familiar declarative, component-oriented programming model. i.e, the solution should not fundamentally change how developers think about writing React, and should generally _remove_ concepts (the need to use React.memo(), useMemo(), and useCallback()) rather than introduce new concepts.
* "Just work" on idiomatic React code that follows React's rules (pure render functions, the rules of hooks, etc).
* Support typical debugging and profiling tools and workflows.
* Be predictable and understandable enough by React developers — i.e. developers should be able to quickly develop a rough intuition of how React Compiler works.
@@ -19,7 +19,7 @@ The idea of React Compiler is to allow developers to use React's familiar declar
The following are explicitly *not* goals for React Compiler:
* Provide perfectly optimal re-rendering with zero unnecessary recomputation. This is a non-goal for several reasons:
* The runtime overhead of the extra tracking involved can outweight the cost of recomputation in many cases.
* The runtime overhead of the extra tracking involved can outweigh the cost of recomputation in many cases.
* In cases with conditional dependencies it may not be possible to avoid recomputing some/all instructions.
* The amount of code may regress startup times, which would conflict with our goal of neutral startup performance.
* Support code that violates React's rules. React's rules exist to help developers build robust, scalable applications and form a contract that allows us to continue improving React without breaking applications. React Compiler depends on these rules to safely transform code, and violations of rules will therefore break React Compiler's optimizations.
@@ -42,9 +42,9 @@ React Compiler has two primary public interfaces: a Babel plugin for transformin
The core of the compiler is largely decoupled from Babel, using its own intermediate representations. The high-level flow is as follows:
- **Babel Plugin**: Determines which functions in a file should be compiled, based on the plugin options and any local opt-in/opt-out directives. For each component or hook to be compiled, the plugin calls the compiler, passing in the original function and getting back a new AST node which will replace the original.
- **Lowering** (BuildHIR): The first step of the compiler is to convert the Babel AST into React Compiler's primary intermediate representation, HIR (High-level Intermediate Representation). This phase is primarily based on the AST itself, but currently leans on Babel to resolve identifiers. The HIR preserves the precise order-of-evaluation semantics of JavaScript, resolves break/continue to their jump points, etc. The resulting HIR forms a control-flow graph of basic blocks, each of which contains zero or more consecutive instructions followed by a terminal. The basic blocks are stored in reverse postorder, such that forward iteration of the blocks allows predecessors to be visited before successors _unless_ there is a "back edge" (ie a loop).
- **Lowering** (BuildHIR): The first step of the compiler is to convert the Babel AST into React Compiler's primary intermediate representation, HIR (High-level Intermediate Representation). This phase is primarily based on the AST itself, but currently leans on Babel to resolve identifiers. The HIR preserves the precise order-of-evaluation semantics of JavaScript, resolves break/continue to their jump points, etc. The resulting HIR forms a control-flow graph of basic blocks, each of which contains zero or more consecutive instructions followed by a terminal. The basic blocks are stored in reverse postorder, such that forward iteration of the blocks allows predecessors to be visited before successors _unless_ there is a "back edge" (i.e. a loop).
- **SSA Conversion** (EnterSSA): The HIR is converted to HIR form, such that all Identifiers in the HIR are updated to an SSA-based identifier.
- Validation: We run various validation passes to check that the input is valid React, ie that it does not break the rules. This includes looking for conditional hook calls, unconditional setState calls, etc.
- Validation: We run various validation passes to check that the input is valid React, i.e. that it does not break the rules. This includes looking for conditional hook calls, unconditional setState calls, etc.
- **Optimization**: Various passes such as dead code elimination and constant propagation can generally improve performance and reduce the amount of instructions to be optimized later.
- **Type Inference** (InferTypes): We run a conservative type inference pass to identify certain key types of data that may appear in the program that are relevant for further analysis, such as which values are hooks, primitives, etc.
- **Inferring Reactive Scopes**: Several passes are involved in determining groups of values that are created/mutated together and the set of instructions involved in creating/mutating those values. We call these groups "reactive scopes", and each can have one or more declarations (or occasionally a reassignment).
The pipeline is fault-tolerant: all passes run to completion, accumulating errors on `Environment` rather than aborting on the first error.
- **Validation passes** are wrapped in `env.tryRecord()` in Pipeline.ts, which catches non-invariant `CompilerError`s and records them. If a validation pass throws, compilation continues.
- **Infrastructure/transformation passes** (enterSSA, eliminateRedundantPhi, inferMutationAliasingEffects, codegen, etc.) are NOT wrapped in `tryRecord()` because subsequent passes depend on their output being structurally valid. If they fail, compilation aborts.
- **`lower()` (BuildHIR)** always produces an `HIRFunction`, recording errors on `env` instead of returning `Err`. Unsupported constructs (e.g., `var`) are lowered best-effort.
- At the end of the pipeline, `env.hasErrors()` determines whether to return `Ok(codegen)` or `Err(aggregatedErrors)`.
## Further Reading
- [MUTABILITY_ALIASING_MODEL.md](../../src/Inference/MUTABILITY_ALIASING_MODEL.md): Detailed aliasing model docs
@@ -24,7 +24,7 @@ The goal of mutability and aliasing inference is to understand the set of instru
In code, the mutability and aliasing model is compromised of the following phases:
*`InferMutationAliasingEffects`. Infers a set of mutation and aliasing effects for each instruction. The approach is to generate a set of candidate effects based purely on the semantics of each instruction and the types of the operands, then use abstract interpretation to determine the actual effects (or errros) that would apply. For example, an instruction that by default has a Capture effect might downgrade to an ImmutableCapture effect if the value is known to be frozen.
*`InferMutationAliasingEffects`. Infers a set of mutation and aliasing effects for each instruction. The approach is to generate a set of candidate effects based purely on the semantics of each instruction and the types of the operands, then use abstract interpretation to determine the actual effects (or errors) that would apply. For example, an instruction that by default has a Capture effect might downgrade to an ImmutableCapture effect if the value is known to be frozen.
*`InferMutationAliasingRanges`. Infers a mutable range (start:end instruction ids) for each value in the program, and annotates each Place with its effect type for usage in later passes. This builds a graph of data flow through the program over time in order to understand which mutations effect which values.
*`InferReactiveScopeVariables`. Given the per-Place effects, determines disjoint sets of values that mutate together and assigns all identifiers in each set to a unique scope, and updates the range to include the ranges of all constituent values.
@@ -69,7 +69,7 @@ Describes the creation of new function value, capturing the given set of mutable
kind:'Apply';
receiver:Place;
function:Place;// same as receiver for function calls
mutatesFunction:boolean;// indicates if this is a type that we consdier to mutate the function itself by default
mutatesFunction:boolean;// indicates if this is a type that we consider to mutate the function itself by default
args:Array<Place|SpreadPattern|Hole>;
into:Place;// where result is stored
signature:FunctionSignature|null;
@@ -526,7 +526,7 @@ Capture c <- a
Intuition: these effects are inverses of each other (capturing into an object, extracting from an object). The result is based on the order of operations:
Capture then CreatFrom is equivalent to Alias: we have to assume that the result _is_ the original value and that a local mutation of the result could mutate the original.
Capture then CreateFrom is equivalent to Alias: we have to assume that the result _is_ the original value and that a local mutation of the result could mutate the original.
@@ -90,22 +89,19 @@ export function validateNoDerivedComputationsInEffects(fn: HIRFunction): void {
validateEffect(
effectFunction.loweredFunc.func,
dependencies,
errors,
fn.env,
);
}
}
}
}
}
if(errors.hasAnyErrors()){
throwerrors;
}
}
functionvalidateEffect(
effectFunction: HIRFunction,
effectDeps: Array<IdentifierId>,
errors: CompilerError,
env: Environment,
):void{
for(constoperandofeffectFunction.context){
if(isSetStateType(operand.identifier)){
@@ -219,13 +215,15 @@ function validateEffect(
}
for(constlocofsetStateLocations){
errors.push({
category: ErrorCategory.EffectDerivationsOfState,
reason:
'Values derived from props and state should be calculated during render, not in an effect. (https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state)',
description: null,
loc,
suggestions: null,
});
env.recordError(
newCompilerErrorDetail({
category: ErrorCategory.EffectDerivationsOfState,
reason:
'Values derived from props and state should be calculated during render, not in an effect. (https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state)',
15 | // Error: mutating frozen value (props, which is frozen after hook call)
> 16 | props.items = [];
| ^^^^^ value cannot be modified
17 |
18 | return <div>{value}</div>;
19 | }
Error: Cannot access refs during render
React refs are values that are not needed for rendering. Refs should only be accessed outside of render, such as in event handlers or effects. Accessing a ref value (the `current` property) during render can cause your component not to update as expected (https://react.dev/reference/react/useRef).
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `x` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
Error: Found missing/extra memoization dependencies
Missing dependencies can cause a value to update less often than it should, resulting in stale UI. Extra dependencies can cause a value to update more often than it should, resulting in performance problems such as excessive renders or effects firing too often.
| ^^^ Unnecessary dependency `key`. Values declared outside of a component/hook should not be listed as dependencies as the component will not re-render if they change
| ^^^^ Unnecessary dependency `init`. Values declared outside of a component/hook should not be listed as dependencies as the component will not re-render if they change
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `options` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.invalid-mutation-in-closure.ts:6:9
4 | options.foo = 'bar';
5 | }
> 6 | return test;
| ^^^^ This function may (indirectly) reassign or modify `options` after render
7 | }
8 |
error.invalid-mutation-in-closure.ts:4:4
2 | function test() {
3 | foo(options.foo); // error should not point on this line
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `x` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `local` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `local` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `local` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
Error: Found missing/extra memoization dependencies
Missing dependencies can cause a value to update less often than it should, resulting in stale UI. Extra dependencies can cause a value to update more often than it should, resulting in performance problems such as excessive renders or effects firing too often.
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `a` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `parentRef` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `onClick` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
@@ -26,14 +28,14 @@ Error: Cannot access refs during render
React refs are values that are not needed for rendering. Refs should only be accessed outside of render, such as in event handlers or effects. Accessing a ref value (the `current` property) during render can cause your component not to update as expected (https://react.dev/reference/react/useRef).
error.validate-mutate-ref-arg-in-render.ts:3:14
1 | // @validateRefAccessDuringRender:true
2 | function Foo(props, ref) {
> 3 | console.log(ref.current);
| ^^^^^^^^^^^ Passing a ref to a function may read its value during render
4 | return <div>{props.bar}</div>;
5 | }
6 |
error.validate-mutate-ref-arg-in-render.ts:5:9
3 |
4 | function Foo(props, ref) {
> 5 | mutate(ref.current);
| ^^^^^^^^^^^ Passing a ref to a function may read its value during render
* Fault tolerance test: two independent errors should both be reported.
*
* Error 1 (BuildHIR): `try/finally` is not supported
* Error 2 (ValidateNoRefAccessInRender): reading ref.current during render
*/
functionComponent(){
constref=useRef(null);
// Error: try/finally (Todo from BuildHIR)
try{
doSomething();
}finally{
cleanup();
}
// Error: reading ref during render
constvalue=ref.current;
return<div>{value}</div>;
}
```
## Error
```
Found 2 errors:
Todo: (BuildHIR::lowerStatement) Handle TryStatement without a catch clause
error.try-finally-and-ref-access.ts:12:2
10 |
11 | // Error: try/finally (Todo from BuildHIR)
> 12 | try {
| ^^^^^
> 13 | doSomething();
| ^^^^^^^^^^^^^^^^^^
> 14 | } finally {
| ^^^^^^^^^^^^^^^^^^
> 15 | cleanup();
| ^^^^^^^^^^^^^^^^^^
> 16 | }
| ^^^^ (BuildHIR::lowerStatement) Handle TryStatement without a catch clause
17 |
18 | // Error: reading ref during render
19 | const value = ref.current;
Error: Cannot access refs during render
React refs are values that are not needed for rendering. Refs should only be accessed outside of render, such as in event handlers or effects. Accessing a ref value (the `current` property) during render can cause your component not to update as expected (https://react.dev/reference/react/useRef).
error.try-finally-and-ref-access.ts:19:16
17 |
18 | // Error: reading ref during render
> 19 | const value = ref.current;
| ^^^^^^^^^^^ Cannot access ref value during render
* Fault tolerance test: three independent errors should all be reported.
*
* Error 1 (BuildHIR): `try/finally` is not supported
* Error 2 (ValidateNoRefAccessInRender): reading ref.current during render
* Error 3 (InferMutationAliasingEffects): Mutation of frozen props
*/
functionComponent(props){
constref=useRef(null);
// Error: try/finally (Todo from BuildHIR)
try{
doWork();
}finally{
cleanup();
}
// Error: reading ref during render
constvalue=ref.current;
// Error: mutating frozen props
props.items=[];
return<div>{value}</div>;
}
```
## Error
```
Found 3 errors:
Todo: (BuildHIR::lowerStatement) Handle TryStatement without a catch clause
error.try-finally-ref-access-and-mutation.ts:13:2
11 |
12 | // Error: try/finally (Todo from BuildHIR)
> 13 | try {
| ^^^^^
> 14 | doWork();
| ^^^^^^^^^^^^^
> 15 | } finally {
| ^^^^^^^^^^^^^
> 16 | cleanup();
| ^^^^^^^^^^^^^
> 17 | }
| ^^^^ (BuildHIR::lowerStatement) Handle TryStatement without a catch clause
18 |
19 | // Error: reading ref during render
20 | const value = ref.current;
Error: This value cannot be modified
Modifying component props or hook arguments is not allowed. Consider using a local variable instead.
error.try-finally-ref-access-and-mutation.ts:23:2
21 |
22 | // Error: mutating frozen props
> 23 | props.items = [];
| ^^^^^ value cannot be modified
24 |
25 | return <div>{value}</div>;
26 | }
Error: Cannot access refs during render
React refs are values that are not needed for rendering. Refs should only be accessed outside of render, such as in event handlers or effects. Accessing a ref value (the `current` property) during render can cause your component not to update as expected (https://react.dev/reference/react/useRef).
* Fault tolerance test: two independent errors should both be reported.
*
* Error 1 (BuildHIR): `var` declarations are not supported (treated as `let`)
* Error 2 (ValidateNoRefAccessInRender): reading ref.current during render
*/
functionComponent(){
constref=useRef(null);
// Error: var declaration (Todo from BuildHIR)
varitems=[1,2,3];
// Error: reading ref during render
constvalue=ref.current;
return(
<div>
{value}
{items.length}
</div>
);
}
```
## Error
```
Found 2 errors:
Todo: (BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration
error.var-declaration-and-ref-access.ts:12:2
10 |
11 | // Error: var declaration (Todo from BuildHIR)
> 12 | var items = [1, 2, 3];
| ^^^^^^^^^^^^^^^^^^^^^^ (BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration
13 |
14 | // Error: reading ref during render
15 | const value = ref.current;
Error: Cannot access refs during render
React refs are values that are not needed for rendering. Refs should only be accessed outside of render, such as in event handlers or effects. Accessing a ref value (the `current` property) during render can cause your component not to update as expected (https://react.dev/reference/react/useRef).
error.var-declaration-and-ref-access.ts:15:16
13 |
14 | // Error: reading ref during render
> 15 | const value = ref.current;
| ^^^^^^^^^^^ Cannot access ref value during render
// Bug: NewExpression default param value should not prevent set-state-in-effect validation
functionComponent({value=newNumber()}){
const[state,setState]=useState(0);
useEffect(()=>{
setState((s)=>s+1);
});
returnstate;
}
```
## Logs
```
{"kind":"CompileError","detail":{"options":{"category":"EffectSetState","reason":"Calling setState synchronously within an effect can trigger cascading renders","description":"Effects are intended to synchronize state between React and external systems such as manually updating the DOM, state management libraries, or other platform APIs. In general, the body of an effect should do one or both of the following:\n* Update external systems with the latest state from React.\n* Subscribe for updates from some external system, calling setState in a callback function when external state changes.\n\nCalling setState synchronously within an effect body causes cascading renders that can hurt performance, and is not recommended. (https://react.dev/learn/you-might-not-need-an-effect)","suggestions":null,"details":[{"kind":"error","loc":{"start":{"line":8,"column":4,"index":313},"end":{"line":8,"column":12,"index":321},"filename":"invalid-setState-in-useEffect-new-expression-default-param.ts","identifierName":"setState"},"message":"Avoid calling setState() directly within an effect"}]}},"fnLoc":null}
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `local` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
Error: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)
Invariant: Unexpected empty block with `goto` terminal
error.invalid-hook-for.ts:4:9
2 | let i = 0;
3 | for (let x = 0; useHook(x) < 10; useHook(i), x++) {
> 4 | i += useHook(x);
| ^^^^^^^ Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)
5 | }
6 | return i;
7 | }
Block bb5 is empty.
Error: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)
error.invalid-hook-for.ts:3:35
error.invalid-hook-for.ts:3:2
1 | function Component(props) {
2 | let i = 0;
> 3 | for (let x = 0; useHook(x) < 10; useHook(i), x++) {
| ^^^^^^^ Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)
'Calling setState from useMemo may trigger an infinite loop',
),
makeTestCaseError('Found extra memoization dependencies'),
],
},
],
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.