Bug: infinite loop when a set state hook is called in a global handler
See original GitHub issueTo be honest, I am not 100% sure it’s a bug. Perhaps my code is badly written but I don’t know why it’s not working or how to rewrite it in the proper way.
React version: 16.12.0
Steps To Reproduce
function Hello() {
const [s, setS] = React.useState(1);
const print = () => {
setS(s + 1);
setTimeout(() => {
window.print();
}, 600);
window.onafterprint = () => {
setS(s - 1);
}
}
return <div>{s}<button onClick={print}>print</button></div>;
}
- Open this jsfiddle https://jsfiddle.net/z4ku39t2/2 or try the code above
- Click Print button and cancel the print dialog
Link to code example: https://jsfiddle.net/z4ku39t2/2
The current behavior
When the setS is called in the onafterprint handler, the app enters an infinite loop with 100% cpu usage so you won’t be able to do anything on the page. The profiler shows that it happens inside React.
The expected behavior
The setS successfully modifies the state and the component re-renders.
Browser: Version 79.0.3945.130 (Official Build) (64-bit)
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:9
Top Results From Across the Web
setState array cause infinite loop - reactjs - Stack Overflow
They either need to be called in hooks(useEffect, useCallback, useLayoutEffect) callbacks or in non render phases, like event handlers.
Read more >How to Solve the Infinite Loop of React.useEffect()
useEffect() React hook manages the side-effects like fetching over the network, manipulating DOM directly, starting and ending timers.
Read more >How to solve the React useEffect Hook's infinite loop patterns
Solve the issue of infinite loops when using the useEffect Hook in React to more smoothly utilize the Hook for your app's side...
Read more >A Complete Guide to Testing React Hooks - Toptal
Hooks were introduced in React 16.8 in late 2018. They are functions that hook into a functional component and allow us to use...
Read more >Too many re-renders. React limits the number ... - Datainfinities
When a state was changed, the component will again be rendered. So, the function setName changes the state which leads to another re-render....
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Last published build from master before #19220 was
0.0.0-33c3af284
which still hangs while it no longer freezes with ##19220.Closing since it the description fits.
Looks this this was actually fixed for React 17 in #19220.