I have below code and help me to find the output with accurate explanation.
'infiniteLoopProtection:false'
import * as React from "react";
import { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";
import { screen, fireEvent } from "@testing-library/dom";
function App() {
const [state, setState] = useState(0)
console.log(1)
const start = Date.now()
while (Date.now() - start < 50) {
window.timestamp = Date.now()
}
useEffect(() => {
console.log(2)
}, [state])
Promise.resolve().then(() => console.log(3))
setTimeout(() => console.log(4), 0)
const onClick = () => {
console.log(5)
setState(num => num + 1)
console.log(6)
}
return <div>
<button onClick={onClick}>click me</button>
</div>
}
const root = createRoot(document.getElementById('root'));
root.render(<App/>)
setTimeout(() => fireEvent.click(screen.getByText('click me')), 100)
Now I am confused how this can be.
Que: How promise and setTimeOut functions are executing before useEffect on initial render but after useEffect on subsequent render?
I tried running it on codeSandbox and got the below output
1
2
3
4
5
6
1
2
3
4
Even I executed the code in codeSandBox and got the same output. But https://bigfrontend.dev/react-quiz/useeffect-timing-iii is not accepting this answer. According to them correct answer should be
1
3
4
2
5
6
1
2
3
4