App.js
import React from "react";
import CounterOne from "./CounterOne";
function App() {
const [display, setDisplay] = React.useState(true);
return (
<>
{display && <CounterOne />}
<button
onClick={() => {
setDisplay(!display);
}}
>
display
</button>
</>
);
}
export default App;
CounterOne.js
import React, { useState } from "react";
function CounterOne() {
const [count, setCount] = useState(0);
React.useEffect(() => {
console.log("component did update");
return () => {
console.log("component will unmount");
};
}, [count]);
return (
<div>
<p>Count is {count}</p>
<button
onClick={() => {
setCount(0);
}}
>
reset
</button>
<button
onClick={() => {
setCount(count + 5);
}}
>
Add 5
</button>
<button
onClick={() => {
setCount(count - 1);
}}
>
Sub 1
</button>
</div>
);
}
export default CounterOne;
When i hit the Add 5 or sub 1 button, the component re-render then in browser console it prints
component will unmount
component did update
i am confuse why will unmount part execute when the update of state taking place
question from:https://stackoverflow.com/questions/65941849/want-to-know-why-compoentwillunmount-execute-when-a-component-update