Sunday 30 October 2022

Why React goes Infinite when I set state in function body?

If we set the state with the same value component won't re-render, but it's not applicable when I set the state in the function body.

For example, if I set the same state on the button click and the button clicked, the component does not re-rendering on the button click

function Test1() {
  const [name, setName] = useState("Shiva");
  const onButtonClick = () => {
    console.log("Clicked");
    setName("Shiva");
  };
  console.log("Redering");
  return (
    <div>
      <span>My name is {name}</span>
      <button onClick={onButtonClick}>Click Me</button>
    </div>
  );
}

But, when I set the same state before the return statement React goes infinite renderings

function Test2() {
  const [name, setName] = useState("Shiva");
  // ... come stuff
  setName("Shiva");
  console.log("Rendering");
  return (
    <div>
      <span>My name is {name}</span>
    </div>
  );
}

What actually happening internally?



from Why React goes Infinite when I set state in function body?

No comments:

Post a Comment