I'm was building a separated service that deals with a complex things, the service is a class that, just for testing proposes, I mock inside a useState
.
The point is that I forgot a console.log
inside the constructor and realize that the class constructor is called so many times as the component is re-rendered. That behavior don't lead to unexpected behavior or something like that, but I'm asking myself WHY this is happening, as I know things declared inside a useState
on it's call don't repeat itself, but apparently I'm wrong what leads to the questions below.
- Why this happens? (I don't find any docs about this specific case)
- Does this affect memory or processing? (Since the class is re-instantiated many times)
- The garbage collector collect that?
I create a little sandbox to example what I'm saying, you can see that the "Called" word is displayed many times on console, and keeps displaying clicking on the button. https://codesandbox.io/s/new-class-inside-usestate-w9et3?file=/src/App.js
It is a common mistake and somewhat not explicitly mentioned in React docs.
On each render the body of function component executed. Logging from the constructor is the expected behaviour, because writing such code:
Will results calling
new Foo()
on every render, yes, although it's result not considered byuseState
hook.Therefore you would like to make lazy initial as you want it to be called once: