Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unmounting functional components in React

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;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading