0
0
Reactframework~10 mins

Unmounting phase in React - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to run cleanup when the component unmounts.

React
useEffect(() => {
  return () => {
    [1];
  };
}, []);
Drag options to blanks, or click blank then click option'
AfetchData()
BsetState(true)
Cconsole.log('Cleanup')
DrenderComponent()
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to update state inside cleanup causes errors.
Not returning a function inside useEffect for cleanup.
2fill in blank
medium

Complete the code to clean up an event listener on unmount.

React
useEffect(() => {
  window.addEventListener('resize', handleResize);
  return () => {
    window.[1]('resize', handleResize);
  };
}, []);
Drag options to blanks, or click blank then click option'
AaddEventListener
BattachEvent
CdispatchEvent
DremoveEventListener
Attempts:
3 left
💡 Hint
Common Mistakes
Using addEventListener again in cleanup causes duplicate listeners.
Forgetting to remove event listeners leads to bugs.
3fill in blank
hard

Fix the error in the cleanup function to avoid memory leaks.

React
useEffect(() => {
  const timer = setTimeout(() => {
    console.log('Timer done');
  }, 1000);
  return () => {
    clearTimeout([1]);
  };
}, []);
Drag options to blanks, or click blank then click option'
AclearTimeout
Btimer
CsetTimeout
Dtimeout
Attempts:
3 left
💡 Hint
Common Mistakes
Using clearInterval instead of clearTimeout for timeouts.
Passing the wrong variable to clearTimeout.
4fill in blank
hard

Fill both blanks to properly clean up a subscription on unmount.

React
useEffect(() => {
  const subscription = api.subscribe(data => setData(data));
  return () => {
    subscription.[1]();
    console.[2]('Unsubscribed');
  };
}, []);
Drag options to blanks, or click blank then click option'
Aunsubscribe
Blog
Cwarn
Dsubscribe
Attempts:
3 left
💡 Hint
Common Mistakes
Calling subscribe instead of unsubscribe in cleanup.
Using console.warn instead of console.log without reason.
5fill in blank
hard

Fill all three blanks to clean up a WebSocket connection on unmount.

React
useEffect(() => {
  const socket = new WebSocket('wss://example.com');
  socket.onmessage = event => setMessage(event.data);
  return () => {
    socket.[1]();
    socket.[2] = null;
    console.[3]('WebSocket closed');
  };
}, []);
Drag options to blanks, or click blank then click option'
Aclose
Bonmessage
Clog
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Calling send instead of close to end the connection.
Not removing the onmessage handler causes memory leaks.