← All React exercises

React quiz · 21

UseEffect() II

StatusNot taken

Question

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

Code

exercise.tsx
1import * as React from 'react';
2import { useState, useRef, useEffect } from 'react';
3import { createRoot } from 'react-dom/client';
4
5function App() {
6  const [show, setShow] = useState(true)
7  return <div>
8    {show && <Child unmount={() => setShow(false)} />}
9  </div>;
10}
11
12function Child({ unmount }) {
13  const isMounted = useIsMounted()
14  useEffect(() => {
15    console.log(isMounted)
16    Promise.resolve(true).then(() => {
17      console.log(isMounted)
18    });
19    unmount();
20  }, []);
21
22  return null;
23};
24
25function useIsMounted() {
26  const isMounted = useRef(false);
27
28  useEffect(() => {
29    isMounted.current = true;
30    return () => isMounted.current = false;
31  }, []);
32
33  return isMounted.current;
34}
35
36const root = createRoot(document.getElementById('root'));
37root.render(<App/>)