Skip to content

React 18 different behavior of ReactDom.createRoot and ReactDom.render #23097

Closed
@mkinfrared

Description

@mkinfrared

React 18.0.0-rc.0

I noticed a different behavior when using new ReactDom.createRoot feature comapared to the current ReactDom.render

So I have this demo project here to illustrate the problem.

The setup is pretty simple. The app component has a boolean state to open/close modal. The modal component calls a custom hook useOutsideClick whick adds a click event listener to the window and calls a callback passed to that hook if the click was triggered outside the ref element which is passed as arguments to that hook.

When I use the current ReactDom.render everything works fine as expected. You click the button, the modal opens, the window click event is added, then you click outside the ref object, the modal is closed. But when I switch to new ReactDom.createRoot which is reccomended when using React 18, I get a different behavior. When I click the button to open a modal, the addEventListener inside useEffect in useOutsideClick is called during the bubbling phase, the modal is mounted, then the click event bubbles up to the window which now has a click event registered, and as the click happened on the button which is outside ref object the modal is closed.

I am not really sure if that new behavior is a bug or a feature but I at least would like to hear some explanation on that.

In indes.tsx file I left the code for createRoot commented out so you could easily switch between these two apis.

Metadata

Metadata

Assignees

No one assigned

    Labels

    React 18Bug reports, questions, and general feedback about React 18Type: Discussion

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions