Home > Enterprise >  How does react js differentiate between component instances?
How does react js differentiate between component instances?

Time:09-14

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?

CodePudding user response:

First, this pattern is super weird:

function homePageTick () {
  root.render(<App/>)
}
setInterval(homePageTick, 1000)

You should call root.render only once, and then use effects and state to change the contents of the app.

Now to your question, when React is rerendering and sees the same component at the same place, it will reuse the existing instance. When React compares the two trees <div><HomePage/></div> and <div><HomePage/></div>, it sees that they are identical (because HomePage === HomePage) and therefore reuses the existing HomePage instance (in order not to lose the internal state). After 10 seconds, when comparing <div><HomePage/></div> and <div><HomePage/><HomePage/></div>, it will reuse the existing HomePage component for the first one, and create a new one for the second one that didn’t exist before.

If you want to force React to create a new instance of the same component, you can give them different key attributes. For instance <HomePage key={this.index}/>.

You can read https://reactjs.org/docs/reconciliation.html for more information.

  • Related