Understanding React's behavior under the hood when an exception occurs #33801
-
Hello. Please help me understand why in the last two versions at least (v18, v19) when an exception occurs in the rendering thread, React tries to re-render the tree exactly four times? Not two times, which seems logical, but exactly four. I understand that this behavior should not be analyzed in principle, since react provides a way to handle these exceptions, so this is more of a research question and I hope you can shed some light on this behavior. Here is the code that illustrates this behavior. Logging works exactly four times with different code modifications.: export function App() {
return <Comp/>
}
export const Comp = () => {
const [state, setState] = useState(() => {
console.log('create instance');
return 1;
});
const flag = true;
if (flag)
throw new Error;
return (
<div>
</div>
)
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
React retries 4 times because it implements a retry strategy for transient errors. It's not 2 because 4 attempts provide better balance between recovering from temporary errors (race conditions, inconsistent state) and performance. This is an internal detail of the Fiber reconciler, your useState executes 4 times because each retry recreates the component. |
Beta Was this translation helpful? Give feedback.
-
Hi! Interesting observation — and great question. This behavior relates to React's error recovery mechanism in concurrent mode (introduced in v18+). When an exception occurs during rendering, React may attempt to recover and retry rendering the component subtree, depending on the error boundary setup and internal heuristics. The "four retries" you're seeing is likely a result of React's internal render phase retry logic, where it progressively backs off or switches rendering lanes to attempt a stable update. This behavior isn't officially documented (and may change across versions), but it aligns with what others have noticed in dev mode:
So while four retries may feel "too specific," it's likely an implementation detail rather than a strict rule. Hope this helps! |
Beta Was this translation helpful? Give feedback.
-
🤔 Why does React re-render exactly four times after a rendering error in recent versions (v18, v19)?Hello! Great question. This behavior is quite interesting and mostly falls into React's internal design for error recovery and development debugging experience. Here's why:
Example:function Comp() {
throw new Error("Render failed");
}
function App() {
return (
<div>
<Comp />
</div>
);
} |
Beta Was this translation helpful? Give feedback.
React retries 4 times because it implements a retry strategy for transient errors. It's not 2 because 4 attempts provide better balance between recovering from temporary errors (race conditions, inconsistent state) and performance. This is an internal detail of the Fiber reconciler, your useState executes 4 times because each retry recreates the component.