Skip to content

Bug: infinite loop when a set state hook is called in a global handler #17918

@OrKoN

Description

@OrKoN

To 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>;
}

  1. Open this jsfiddle https://jsfiddle.net/z4ku39t2/2 or try the code above
  2. 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)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions