2

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.

free-stack
  • 21
  • 2

1 Answers1

0

Expected Behavior

console.log('My Log') is in the body of the functional component. Thus, any time a parent state changes, component state updates occur, or component reconciliations occur, that "My Log" console log will get called. This is why "My Log" gets called when you change from "posts" to "users".

Your Example - not logging again

The reason your "My Log" is not logging again and again is because you aren't actually changing the state when you keep clicking the button. If you 'change' state from "users" to "users", React will know that the component does not require a re-render, because state hasn't actually been updated. This is part of the design of React's reconciliation process.

fordat
  • 355
  • 4
  • 13