skip to Main Content

I am new to React. I am trying out an exercise. In my app I have a button that toggles the appearance of a black box. I want the onBlackBoxUnmount function to be executed when the BackBox component is unmounted. However, I notice that it is executed every time I click the button. What does this happen.

import React, { useState, useEffect } from "react";

function MouseContainer() {
  const [seeBox, setSeeBox] = useState(true);
  return (
    <>
      <button onClick={() => setSeeBox(!seeBox)}>Toggle Black Box</button>
      {seeBox && <BlackBox></BlackBox>}
    </>
  );
}

function BlackBox() {
  const onBackBoxUnmount = () => {
    console.log("clean up code ...");
  };
  useEffect(() => {
    return onBackBoxUnmount;
  });
  return (
    <div style={{ backgroundColor: "black", height: 100, width: 100 }}></div>
  );
}

export default MouseContainer;

2

Answers


  1. You will need to pass in an empty dependency array in the useEffect.

    Something like this:

    useEffect(() => {
      ...
    }, [])
    
    Login or Signup to reply.
  2. You set it up right!
    It will be executed everytime you unmount your component.
    But as you said, even when seeBox is FALSE so I don’t think the problem is the component but React StrictMode.
    Docs

    Your components will re-render an extra time to find bugs caused by impure rendering.

    This could be the problem. and make it console log twice.

    You can find if it is Enabled or not by look at App.tsx (or App.js).
    If your app is wrapped in StrictMode component. just delete it and check again.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search