admin管理员组文章数量:1312795
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".
本文标签:
版权声明:本文标题:javascript - What exactly does it mean that a component unmounts in React? Does it disappear after it's unmounted? - Sta 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741821720a2399404.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论