I thought the useEffect cleanup function would only be triggered when the component is literally unmounted(not updating) from the DOM.
But the truth is when the component is updated, the useEffect cleanup function will be triggered once and then the useEffect function will also be triggered.
I thought when the component first rendered to the DOM, the useEffect function, the useEffect cleanup function and useEffect function will be triggered sequentially. But the truth is it would only have this situation when the entire <App /> is wrapped by <StrictMode />
This one is the most straightforward one. The console.log will be a sequence.
function Child() {
console.log("Child Before useEffect");
console.log("Child After useEffect");
return <div>Child</div>;
}
function App() {
console.log("App Before useEffect");
console.log("App After useEffect");
return (
<div>
<Child />
</div>
);
}
/*
App Before useEffect
App After useEffect
Child Before useEffect
Child After useEffect
*/
function Child() {
console.log("Child Before useEffect");
React.useEffect(() => {
console.log("Child useEffect");
return () => {
console.log("Child useEffect Cleanup");
};
}, []);
console.log("Child After useEffect");
return <div>Child</div>;
}
function App() {
console.log("App Before useEffect");
React.useEffect(() => {
console.log("App useEffect");
return () => {
console.log("App useEffect Cleanup");
};
}, []);
console.log("App After useEffect");
return (
<div>
<Child />
</div>
);
}
/**
App Before useEffect
App After useEffect
Child Before useEffect
Child After useEffect
Child useEffect
App useEffect
*/