Skip to content

Commit d083ec1

Browse files
potetoraashish1601
andauthored
[compiler] Allow setState after await in effect functions (react#36734)
`react-hooks/set-state-in-effect` flagged setState calls that happen after an `await` inside an async function invoked from an effect. Post-await code resumes in a microtask after the effect body has returned, so the "synchronous setState cascades a render" rationale does not apply; the lint was a false positive on a common data-loading shape (15 reactions on the issue). The fix exempts a setState only when it is *provably* post-await: a forward must-dataflow over the HIR CFG computes the blocks that begin after an await has executed on every path from the function entry (optimistic initialization so loop back-edges do not pessimize the meet, fixpoint to the greatest solution), plus an intra-block flag for instructions after an Await in the same block. A setState reachable on any await-free path still flags, so the conditional-await case remains an error by design, with a fixture documenting that choice. Suppression is sound under try/catch because HIRBuilder terminates blocks after each instruction in a try region, and an awaited rejection also resumes in a microtask. Fixtures: post-await setState (event gone), setState before the first await (still flags), setState after a conditional await (still flags). First commit documents the false positive via the lint-mode logger output, second removes it. Builds on the approach in react#36417 by @raashish1601, hardened from a seen-await flag to the path-sensitive analysis above. Implemented identically in the TypeScript compiler and the Rust port. Verification: TS snap 1807/1807, Rust snap 1807/1807, cargo workspace green, scoped TS-vs-Rust HIR parity harness green. Closes react#34905 --------- Co-authored-by: Raashish Aggarwal <94279692+raashish1601@users.noreply.github.com>
1 parent 8b0da1c commit d083ec1

8 files changed

Lines changed: 399 additions & 0 deletions

‎compiler/crates/react_compiler_validation/src/validate_no_set_state_in_effects.rs‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,11 @@ fn get_set_state_call(
376376
source_code: Option<&str>,
377377
) -> Result<Option<SetStateInfo>, CompilerDiagnostic> {
378378
let mut ref_derived_values: FxHashSet<IdentifierId> = FxHashSet::default();
379+
let blocks_after_await: Option<FxHashSet<BlockId>> = if func.is_async {
380+
Some(compute_blocks_starting_after_await(func))
381+
} else {
382+
None
383+
};
379384

380385
// First pass: collect ref-derived values (needed before building control dominator checker)
381386
// We do a pre-pass to seed ref_derived_values so the control dominator checker has them.
@@ -481,6 +486,9 @@ fn get_set_state_call(
481486
}
482487
}
483488

489+
let mut is_after_await = blocks_after_await
490+
.as_ref()
491+
.is_some_and(|blocks| blocks.contains(&block.id));
484492
for &instr_id in &block.instructions {
485493
let instr = &func.instructions[instr_id.0 as usize];
486494

@@ -519,6 +527,9 @@ fn get_set_state_call(
519527
}
520528

521529
match &instr.value {
530+
InstructionValue::Await { .. } => {
531+
is_after_await = true;
532+
}
522533
InstructionValue::LoadLocal { place, .. } => {
523534
if set_state_functions.contains_key(&place.identifier) {
524535
let info = set_state_functions[&place.identifier].clone();
@@ -536,6 +547,12 @@ fn get_set_state_call(
536547
if is_set_state_type_by_id(callee.identifier, identifiers, types)
537548
|| set_state_functions.contains_key(&callee.identifier)
538549
{
550+
if is_after_await {
551+
// Code that is only reachable after an await resumes in a
552+
// microtask after the effect body has returned, so calling
553+
// setState there cannot synchronously cascade a re-render.
554+
continue;
555+
}
539556
if enable_allow_set_state_from_refs {
540557
// Check if the first argument is ref-derived
541558
if let Some(first_arg) = args.first() {
@@ -577,3 +594,62 @@ fn get_set_state_call(
577594
}
578595
Ok(None)
579596
}
597+
598+
/// Computes the set of blocks which begin after an `await` has executed on
599+
/// *every* control flow path from the function entry. Instructions in such
600+
/// blocks (and instructions following an Await within any block) are
601+
/// guaranteed to run asynchronously, in a microtask after the synchronous
602+
/// portion of the function has returned.
603+
///
604+
/// This is a forward must-dataflow: a block starts after an await iff all of
605+
/// its predecessors end after an await. Suppression based on this analysis is
606+
/// sound in the presence of try/catch because HirBuilder::push terminates the
607+
/// current block after every instruction within a try region: a MaybeThrow
608+
/// block can therefore only throw from its single instruction, and when that
609+
/// instruction is an Await the rejection also resumes in a microtask.
610+
///
611+
/// Port of computeBlocksStartingAfterAwait in ValidateNoSetStateInEffects.ts.
612+
fn compute_blocks_starting_after_await(func: &HirFunction) -> FxHashSet<BlockId> {
613+
let mut blocks_with_await: FxHashSet<BlockId> = FxHashSet::default();
614+
for (block_id, block) in &func.body.blocks {
615+
let has_await = block.instructions.iter().any(|&instr_id| {
616+
matches!(
617+
func.instructions[instr_id.0 as usize].value,
618+
InstructionValue::Await { .. }
619+
)
620+
});
621+
if has_await {
622+
blocks_with_await.insert(*block_id);
623+
}
624+
}
625+
// Initialize non-entry blocks optimistically so that loop back-edges do
626+
// not pessimize the meet; the fixpoint then lowers any block reachable
627+
// without passing an await.
628+
let mut starts_after_await: FxHashMap<BlockId, bool> = FxHashMap::default();
629+
for (block_id, _block) in &func.body.blocks {
630+
starts_after_await.insert(*block_id, *block_id != func.body.entry);
631+
}
632+
let mut changed = true;
633+
while changed {
634+
changed = false;
635+
for (block_id, block) in &func.body.blocks {
636+
if *block_id == func.body.entry {
637+
continue;
638+
}
639+
let start_after_await = !block.preds.is_empty()
640+
&& block.preds.iter().all(|pred| {
641+
starts_after_await.get(pred).copied().unwrap_or(false)
642+
|| blocks_with_await.contains(pred)
643+
});
644+
if starts_after_await.get(block_id) != Some(&start_after_await) {
645+
starts_after_await.insert(*block_id, start_after_await);
646+
changed = true;
647+
}
648+
}
649+
}
650+
starts_after_await
651+
.into_iter()
652+
.filter(|&(_, after_await)| after_await)
653+
.map(|(block_id, _)| block_id)
654+
.collect()
655+
}

‎compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoSetStateInEffects.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,9 @@ function getSetStateCall(
193193
const enableAllowSetStateFromRefsInEffects =
194194
env.config.enableAllowSetStateFromRefsInEffects;
195195
const refDerivedValues: Set<IdentifierId> = new Set();
196+
const blocksAfterAwait = fn.async
197+
? computeBlocksStartingAfterAwait(fn)
198+
: null;
196199

197200
const isDerivedFromRef = (place: Place): boolean => {
198201
return (
@@ -232,6 +235,7 @@ function getSetStateCall(
232235
}
233236
}
234237
}
238+
let isAfterAwait = blocksAfterAwait?.has(block.id) ?? false;
235239
for (const instr of block.instructions) {
236240
if (enableAllowSetStateFromRefsInEffects) {
237241
const hasRefOperand = Iterable_some(
@@ -288,6 +292,10 @@ function getSetStateCall(
288292
}
289293

290294
switch (instr.value.kind) {
295+
case 'Await': {
296+
isAfterAwait = true;
297+
break;
298+
}
291299
case 'LoadLocal': {
292300
if (setStateFunctions.has(instr.value.place.identifier.id)) {
293301
setStateFunctions.set(
@@ -316,6 +324,14 @@ function getSetStateCall(
316324
isSetStateType(callee.identifier) ||
317325
setStateFunctions.has(callee.identifier.id)
318326
) {
327+
if (isAfterAwait) {
328+
/**
329+
* Code that is only reachable after an await resumes in a
330+
* microtask after the effect body has returned, so calling
331+
* setState there cannot synchronously cascade a re-render.
332+
*/
333+
break;
334+
}
319335
if (enableAllowSetStateFromRefsInEffects) {
320336
const arg = instr.value.args.at(0);
321337
if (
@@ -345,3 +361,62 @@ function getSetStateCall(
345361
}
346362
return null;
347363
}
364+
365+
/**
366+
* Computes the set of blocks which begin after an `await` has executed on
367+
* *every* control flow path from the function entry. Instructions in such
368+
* blocks (and instructions following an Await within any block) are guaranteed
369+
* to run asynchronously, in a microtask after the synchronous portion of the
370+
* function has returned.
371+
*
372+
* This is a forward must-dataflow: a block starts after an await iff all of
373+
* its predecessors end after an await. Suppression based on this analysis is
374+
* sound in the presence of try/catch because HIRBuilder.push terminates the
375+
* current block after every instruction within a try region: a maybe-throw
376+
* block can therefore only throw from its single instruction, and when that
377+
* instruction is an Await the rejection also resumes in a microtask.
378+
*/
379+
function computeBlocksStartingAfterAwait(fn: HIRFunction): Set<BlockId> {
380+
const blocksWithAwait = new Set<BlockId>();
381+
for (const [id, block] of fn.body.blocks) {
382+
if (block.instructions.some(instr => instr.value.kind === 'Await')) {
383+
blocksWithAwait.add(id);
384+
}
385+
}
386+
/*
387+
* Initialize non-entry blocks optimistically so that loop back-edges do not
388+
* pessimize the meet; the fixpoint then lowers any block reachable without
389+
* passing an await.
390+
*/
391+
const startsAfterAwait = new Map<BlockId, boolean>();
392+
for (const [id] of fn.body.blocks) {
393+
startsAfterAwait.set(id, id !== fn.body.entry);
394+
}
395+
let changed = true;
396+
while (changed) {
397+
changed = false;
398+
for (const [id, block] of fn.body.blocks) {
399+
if (id === fn.body.entry) {
400+
continue;
401+
}
402+
let startAfterAwait = block.preds.size !== 0;
403+
for (const pred of block.preds) {
404+
if (startsAfterAwait.get(pred) !== true && !blocksWithAwait.has(pred)) {
405+
startAfterAwait = false;
406+
break;
407+
}
408+
}
409+
if (startAfterAwait !== startsAfterAwait.get(id)) {
410+
startsAfterAwait.set(id, startAfterAwait);
411+
changed = true;
412+
}
413+
}
414+
}
415+
const result = new Set<BlockId>();
416+
for (const [id, afterAwait] of startsAfterAwait) {
417+
if (afterAwait) {
418+
result.add(id);
419+
}
420+
}
421+
return result;
422+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
2+
## Input
3+
4+
```javascript
5+
// @loggerTestOnly @validateNoSetStateInEffects @outputMode:"lint"
6+
import {useEffect, useState} from 'react';
7+
8+
function Component({delay}) {
9+
const [ready, setReady] = useState(false);
10+
const load = async () => {
11+
if (delay) {
12+
await Promise.resolve();
13+
}
14+
// The path where `delay` is false reaches this setState without passing an
15+
// await, so it can still execute synchronously within the effect: flag it.
16+
setReady(true);
17+
};
18+
useEffect(() => {
19+
load();
20+
}, [load]);
21+
return ready ? 'Ready' : 'Loading';
22+
}
23+
24+
export const FIXTURE_ENTRYPOINT = {
25+
fn: Component,
26+
params: [{delay: false}],
27+
};
28+
29+
```
30+
31+
## Code
32+
33+
```javascript
34+
// @loggerTestOnly @validateNoSetStateInEffects @outputMode:"lint"
35+
import { useEffect, useState } from "react";
36+
37+
function Component({ delay }) {
38+
const [ready, setReady] = useState(false);
39+
const load = async () => {
40+
if (delay) {
41+
await Promise.resolve();
42+
}
43+
// The path where `delay` is false reaches this setState without passing an
44+
// await, so it can still execute synchronously within the effect: flag it.
45+
setReady(true);
46+
};
47+
useEffect(() => {
48+
load();
49+
}, [load]);
50+
return ready ? "Ready" : "Loading";
51+
}
52+
53+
export const FIXTURE_ENTRYPOINT = {
54+
fn: Component,
55+
params: [{ delay: false }],
56+
};
57+
58+
```
59+
60+
## Logs
61+
62+
```
63+
{"kind":"CompileError","detail":{"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)","severity":"Error","suggestions":null,"details":[{"kind":"error","loc":{"start":{"line":15,"column":4,"index":478},"end":{"line":15,"column":8,"index":482},"filename":"invalid-setState-in-useEffect-after-conditional-await.ts","identifierName":"load"},"message":"Avoid calling setState() directly within an effect"}]},"fnLoc":null}
64+
{"kind":"CompileSuccess","fnLoc":{"start":{"line":4,"column":0,"index":111},"end":{"line":18,"column":1,"index":539},"filename":"invalid-setState-in-useEffect-after-conditional-await.ts"},"fnName":"Component","memoSlots":5,"memoBlocks":2,"memoValues":3,"prunedMemoBlocks":0,"prunedMemoValues":0}
65+
```
66+
67+
### Eval output
68+
(kind: ok) "Ready"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// @loggerTestOnly @validateNoSetStateInEffects @outputMode:"lint"
2+
import {useEffect, useState} from 'react';
3+
4+
function Component({delay}) {
5+
const [ready, setReady] = useState(false);
6+
const load = async () => {
7+
if (delay) {
8+
await Promise.resolve();
9+
}
10+
// The path where `delay` is false reaches this setState without passing an
11+
// await, so it can still execute synchronously within the effect: flag it.
12+
setReady(true);
13+
};
14+
useEffect(() => {
15+
load();
16+
}, [load]);
17+
return ready ? 'Ready' : 'Loading';
18+
}
19+
20+
export const FIXTURE_ENTRYPOINT = {
21+
fn: Component,
22+
params: [{delay: false}],
23+
};
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
2+
## Input
3+
4+
```javascript
5+
// @loggerTestOnly @validateNoSetStateInEffects @outputMode:"lint"
6+
import {useEffect, useState} from 'react';
7+
8+
function Component() {
9+
const [ready, setReady] = useState(false);
10+
const load = async () => {
11+
setReady(true);
12+
await Promise.resolve();
13+
};
14+
useEffect(() => {
15+
load();
16+
}, [load]);
17+
return ready ? 'Ready' : 'Loading';
18+
}
19+
20+
export const FIXTURE_ENTRYPOINT = {
21+
fn: Component,
22+
params: [],
23+
};
24+
25+
```
26+
27+
## Code
28+
29+
```javascript
30+
// @loggerTestOnly @validateNoSetStateInEffects @outputMode:"lint"
31+
import { useEffect, useState } from "react";
32+
33+
function Component() {
34+
const [ready, setReady] = useState(false);
35+
const load = async () => {
36+
setReady(true);
37+
await Promise.resolve();
38+
};
39+
useEffect(() => {
40+
load();
41+
}, [load]);
42+
return ready ? "Ready" : "Loading";
43+
}
44+
45+
export const FIXTURE_ENTRYPOINT = {
46+
fn: Component,
47+
params: [],
48+
};
49+
50+
```
51+
52+
## Logs
53+
54+
```
55+
{"kind":"CompileError","detail":{"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)","severity":"Error","suggestions":null,"details":[{"kind":"error","loc":{"start":{"line":11,"column":4,"index":286},"end":{"line":11,"column":8,"index":290},"filename":"invalid-setState-in-useEffect-before-await.ts","identifierName":"load"},"message":"Avoid calling setState() directly within an effect"}]},"fnLoc":null}
56+
{"kind":"CompileSuccess","fnLoc":{"start":{"line":4,"column":0,"index":111},"end":{"line":14,"column":1,"index":347},"filename":"invalid-setState-in-useEffect-before-await.ts"},"fnName":"Component","memoSlots":3,"memoBlocks":2,"memoValues":3,"prunedMemoBlocks":0,"prunedMemoValues":0}
57+
```
58+
59+
### Eval output
60+
(kind: ok) "Ready"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// @loggerTestOnly @validateNoSetStateInEffects @outputMode:"lint"
2+
import {useEffect, useState} from 'react';
3+
4+
function Component() {
5+
const [ready, setReady] = useState(false);
6+
const load = async () => {
7+
setReady(true);
8+
await Promise.resolve();
9+
};
10+
useEffect(() => {
11+
load();
12+
}, [load]);
13+
return ready ? 'Ready' : 'Loading';
14+
}
15+
16+
export const FIXTURE_ENTRYPOINT = {
17+
fn: Component,
18+
params: [],
19+
};

0 commit comments

Comments
 (0)