let say I have a functional Home
ponent:
const Home = () => {
console.log('outside useEffect')
useEffect(() => {
console.log('inside useEffect')
// cleanup function
return () => { console.log('unmounted') }
}, [])
return <div>Hello Word</div>
}
The output in the console shows:
outside useEffect
inside useEffect
unmounted
inside useEffect
My questions are:
- When does the ponent
unmount
, does it happen automatically after it has rendered once or when? - What exactly does happen when the ponent
unmounts
? Does the ponent get deleted/removed? If yes then how am I still able to see theHello World
even if itunmounts
.
let say I have a functional Home
ponent:
const Home = () => {
console.log('outside useEffect')
useEffect(() => {
console.log('inside useEffect')
// cleanup function
return () => { console.log('unmounted') }
}, [])
return <div>Hello Word</div>
}
The output in the console shows:
outside useEffect
inside useEffect
unmounted
inside useEffect
My questions are:
- When does the ponent
unmount
, does it happen automatically after it has rendered once or when? - What exactly does happen when the ponent
unmounts
? Does the ponent get deleted/removed? If yes then how am I still able to see theHello World
even if itunmounts
.
2 Answers
Reset to default 8Normally a ponent gets unmounted when for example it's rendered conditionally and the conditional bee false
. DummyComponent
below gets unmounted every time state
bee false
. And when a ponent is unmounted, it's removed from the DOM
, and therefore you won't see it in the page.
const DummyComponent = () => {
useEffect(() => {
console.log("mounted");
return () => {
console.log("unmounted");
};
}, []);
return <div>Hello Word</div>;
};
const App = () => {
const [state, setState] = useState(true);
return (
<div>
<button onClick={() => setState(!state)}>Toggle Dummy Component</button>
{state ? <DummyComponent /> : <></>}
</div>
);
};
What you are seeing in your case is introduced by React version 18
where each ponent gets mounted
and immediately unmounted and mounted again, when you are in development with StrictMode
: it's explained in this thread. And it's so quick that you are not noticing the change visually.
In React 18 Strict Mode, each ponent is unmounted & remounted again.
https://reactjs/blog/2022/03/29/react-v18.html
Perhaps that's why "inside useEffect" is printed after "unmount".