determine event order in React onEvent properties

determine event order in React onEvent properties

Problem Description:

Imagine an HTML element like the following:

<a onClick={() => console.log("side effect that needs to fire before the redirect"} href="">Click me</a>

Here the event onClick gets executed before the user is redirected. Is this always the case or is this undefined or does this depend on the browser?

Solution – 1

Is this always the case…

Yes, the default action of an event (such as following a link), if any, is not triggered until the event handlers have been called, not least because the event handlers could prevent it from happening by calling preventDefault on the event object.

Beware, though, that when the page is being left, (almost) any outstanding asynchronous work will be terminated. So your event handler can’t (for instance) send a standard ajax request to the server; when the handler returns, that work is still in progress, and will be terminated when the page is torn down. (One exception to that is a beacon.)

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.