Suppose we have one file HomePage.js:
export default class HomePage extends Component {
constructor(props) {
super(props)
this.index = 0
}
render() {
return (
<p>This is the home page number: {this.index++}</p>
)
}
}
and another one App.js:
import React, { Component } from "react";
import { createRoot } from 'react-dom/client';
import HomePage from "./HomePage";
export default class App extends Component {
constructor(props) {
super(props)
this.index = 0
}
render() {
if (this.index++ < 10)
return (
<div>
<HomePage />
</div>
)
return (
<div>
<HomePage />
<HomePage />
</div>
)
}
}
function homePageTick () {
const element = (
<App />
)
root.render(element)
}
const appDiv = document.getElementById("app")
const root = createRoot(appDiv)
setInterval(homePageTick, 1000)
Excuse me for the long piece of code but it's necessary to explain my question.
To sum up what the code actually does:
I believe, at first, it creates one HomePage instance, whose counter starts from zero and counts up. After 10 seconds, it creates another HomePage instance, whose counter starts from zero and counts up.
This blew my mind! I thought that each second, a new HomePage instance will be created and, thus, the counters will only show zero! How does react know which instance is which? How does it know it does not need to create a new instance until 10 seconds later? How could I create a new instance to replace the first, restarting the counter?