You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[compiler] Add enableUseKeyedState flag and improve setState-in-render errors (#35230)
Adds a new `enableUseKeyedState` compiler flag that changes the error
message for unconditional setState calls during render.
When `enableUseKeyedState` is enabled, the error recommends using
`useKeyedState(initialState, key)` to reset state when dependencies
change. When disabled (the default), it links to the React docs for the
manual pattern of storing previous values in state.
Both error messages now include helpful bullet points explaining the two
main alternatives:
1. Use useKeyedState (or manual pattern) to reset state when other
state/props change
2. Compute derived data directly during render without using state
DiffTrain build for [f99241b](f99241b)
@@ -50146,16 +50147,35 @@ function validateNoSetStateInRenderImpl(fn, unconditionalSetStateFunctions) {
50146
50147
}));
50147
50148
}
50148
50149
else if (unconditionalBlocks.has(block.id)) {
50149
-
errors.pushDiagnostic(CompilerDiagnostic.create({
50150
-
category: ErrorCategory.RenderSetState,
50151
-
reason: 'Calling setState during render may trigger an infinite loop',
50152
-
description: 'Calling setState during render will trigger another render, and can lead to infinite loops. (https://react.dev/reference/react/useState)',
description: 'Calling setState during render may trigger an infinite loop.\n' +
50156
+
'* To reset state when other state/props change, use `const [state, setState] = useKeyedState(initialState, key)` to reset `state` when `key` changes.\n' +
50157
+
'* To derive data from other state/props, compute the derived data during render without using state',
50158
+
suggestions: null,
50159
+
}).withDetails({
50160
+
kind: 'error',
50161
+
loc: callee.loc,
50162
+
message: 'Found setState() in render',
50163
+
}));
50164
+
}
50165
+
else {
50166
+
errors.pushDiagnostic(CompilerDiagnostic.create({
50167
+
category: ErrorCategory.RenderSetState,
50168
+
reason: 'Cannot call setState during render',
50169
+
description: 'Calling setState during render may trigger an infinite loop.\n' +
50170
+
'* To reset state when other state/props change, store the previous value in state and update conditionally: https://react.dev/reference/react/useState#storing-information-from-previous-renders\n' +
50171
+
'* To derive data from other state/props, compute the derived data during render without using state',
0 commit comments