Effect setup and cleanup across commits
Without development Strict Mode, mount, wait for effects, click Switch, wait for effects, then click Remove. List the console logs.
Code Snippet
import { useEffect, useState } from "react";
function Room({ id }) {
useEffect(() => {
console.log("connect", id);
return () => console.log("disconnect", id);
}, [id]);
return <p>{id}</p>;
}
export default function App() {
const [id, setId] = useState("A");
const [show, setShow] = useState(true);
return <>
{show && <Room id={id} />}
<button onClick={() => setId("B")}>Switch</button>
<button onClick={() => setShow(false)}>Remove</button>
</>;
}Expected Output & Explanation
connect A
disconnect A
connect B
disconnect B The old cleanup closes over A and runs before the new B setup. Unmount then runs B’s cleanup.
Module Context & References
React · Predict the behavior Trace state queues, stale snapshots, keys, effects and refs
Personal Notes · Markdown