What will be the output of the following component under react strict-mode?
import { useEffect } from "react";
export default function Learn() {
let x = 1;
console.log("outside ", x)
useEffect(() => {
console.log(x);
x = 2;
return () => console.log("destruct", x)
}, []);
console.log("end of fn ", x)
return (
<>
<p>value = {x}</p>
</>
);
}
I ran it on my machine and I got
outside 1
end of fn 1
outside 1
end of fn 1
1
destruct 2
2
But I can’t understand why. As per my reasoning, it should’ve been
outside 1
end of fn 1
1
destruct 2
outside 1
end of fn 1
1
What I assumed (incorrectly) was that react strict mode will:
- Start adding the component to Virtual DOM.
- Once mounting is done, it’ll call the useState hook.
- repeats (1) and (2) again.
But that is not happening here. So what is happening here?