1

Why setting state to same value executes the body of the component?

here is the demo: https://codesandbox.io/s/react-fake-render-lcrcpd

  1. Why setting the state to the same value "t" causes "rerender"?
  2. Why console.log in the body of the component logs 3, but the rendered value is 2?
  3. Why the effect without dependency does not get triggered when the log in the body shows 3?
  4. Does that mean it is not safe to update ref's value directly in the body of the component?

First time clicking the button displays render count 2 -> 4, it skips 3, because it is the previous known value, but not the one that is rendered

Oktay Yuzcan
  • 2,097
  • 1
  • 6
  • 15
  • React is at leisure to call your component function as many times as it likes (and it will happily do so twice in strict mode). That's why they should be side effect free – and yours isn't, since it's mutating that boxed ref. – AKX Jun 29 '23 at 08:44
  • @AKX Why so? Is it mentioned somewhere in the documentation that it is free to call the component without updating the Virtual DOM and executing the side effects? I don't think there is something strange in my code that react does not accept. I should be able to mutate that ref freely. – Oktay Yuzcan Jun 29 '23 at 09:01
  • Yes: https://react.dev/blog/2022/03/08/react-18-upgrade-guide#updates-to-strict-mode – AKX Jun 29 '23 at 10:03
  • @AKX but there is no strict mode in my example – Oktay Yuzcan Jun 29 '23 at 10:41
  • You're using `createRoot`. Same effect. – AKX Jun 29 '23 at 11:16
  • @AKX but it works like this even on version 16.8, when hooks are introduced, when ```createRoot``` didn't even exist. Are you saying that react just works that way? It just randomly executes the body of the component whenever it decides? There are plenty of resources online that uses same approach like me to track render count, does that mean all of them are not valid? Where this behavior is mentioned? – Oktay Yuzcan Jun 29 '23 at 11:43
  • Not randomly, but yes, React works that way. And yes, tracking how many times your function is called is likely pointless, and those resources are likely wrong. – AKX Jun 29 '23 at 11:45
  • @AKX what that execution is called, it is not rerendering. If not randomly, then when? In my example if the initial value of the state was the value that I am setting inside the effect ("t"), that behavior wouldn't happen. Why is that? – Oktay Yuzcan Jun 29 '23 at 12:37

0 Answers0