← All React exercises

React quiz · 14

Async event handler

StatusNot taken

Question

What does the code snippet to the right output by console.log?

Code

exercise.tsx
1// This is a React Quiz from BFE.dev 
2
3import * as React from 'react'
4import { useState } from 'react'
5import { createRoot } from "react-dom/client";
6import { screen, fireEvent } from "@testing-library/dom"
7
8function App() {
9  const [state, setState] = useState(0)
10  const increment = () => {
11    setTimeout(() => {
12      setState(state + 1)
13    }, 100)
14  }
15  console.log(state)
16  return <div>
17    <button onClick={increment}>click me</button>
18  </div>
19}
20
21const root = createRoot(document.getElementById('root'))
22root.render(<App/>)
23
24;(async () => {
25  const action = await screen.findByText('click me')
26  // click the button twice
27  fireEvent.click(action)
28  await wait(50);
29  fireEvent.click(action)
30  await wait(50);
31})()
32
33function wait(duration = 100) {
34  return new Promise((resolve) => setTimeout(resolve, duration));
35}