My problem
The code is simple. When you switch to any new button, it will log the updated sourceType, then "My Log".
You start off at the posts tab, then you clicked users tab, it will log "users" and "My log", which I expect. Then if you click on "users" button again, why does it log "My Log"? Then if you click "users" button again, no matter how many times, why does it log nothing?
Does it have anything to do with lifecycles? Help me out here, thank you!
import React, { useState, useEffect } from "react";
export default function App() {
const [sourceType, setSourceType] = useState("posts");
useEffect(() => {
console.log(sourceType);
}, [sourceType]);
console.log("My Log");
return (
<div>
<button
onClick={() => {
setSourceType("posts");
}}
>
{" "}
Posts{" "}
</button>
<button
onClick={() => {
setSourceType("users");
}}
>
{" "}
Users{" "}
</button>
<button
onClick={() => {
setSourceType("comments");
}}
>
{" "}
Comments{" "}
</button>
<h1> {sourceType} </h1>
</div>
);
}
My expectation
When you are already in the new tab or button, I expect that it will not cause rerender, so it should not print "My Log", but it did.
So, I continue to click. I expect it to be consistant to print, but it does not print "my log" anymore. I understand that it is great for performance. But I don't undertsand why it logged before.