Skip to content

Bug: Click event using window.addEventListener is fired prematurely #24657

Description

@RobinMalfait

React version:

  • Works in React v17.1.0
  • Doesn't work in React v18.0.0 & v18.1.0

Steps To Reproduce

Link to code example:

The current behavior

If you open the React 18 CodeSandbox link from above, what you will notice when you hit the Open Dialog button is that you will receive an event like Got event in <Dialog />!

I tried to minimize the reproduction, the idea is that we have a Dialog component that receives an open prop, based on this prop we know to show the Dialog or not. However a Dialog should also have "outside click" behaviour, to fake this I setup a window.addEventListener('click') inside a useEffect to "capture" this behaviour. However when I click the Open Dialog button this is what happens:

  1. Click Open Dialog
  2. Set open state to true
  3. Re-render component
  4. Pass open={true} to the Dialog component
  5. In a useEffect, setup the window.addEventListener('click') if the open value is true
  6. The callback of the event listener receives the click event from step 1.

Console logs after clicking once on the Open Dialog button:

Open: false
*onClick*
Open: true
Got event in <Dialog />!

The expected behavior

If you open the React 17 CodeSandbox and repeat those steps from above, then you will see the expected behaviour where clicking on the Open Dialog does not trigger the log from within the window.addEventListener('click') it's only the second time that you click that button that it will log something because now the Dialog is considered in an open state.

Console logs after clicking once on the Open Dialog button:

Open: false
*onClick*
Open: true

Is this a bug, a regression or am I doing something incorrect here? I'm confused how a window.addEventListener can receive an event from a click that happened before the listener was even setup 🤔

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions