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
Because when you change a state in a component, React will re-render the whole component. So the old component will be unmounted first, triggering the return callback in useEffect. When a new component is mounted, the logic inside useEffect will be triggered again, hence you see the "component did update" after the "component will unmount" message. More on useEffect here What is the expected return of `useEffect` used for?.