Search code examples
javascriptreactjscomponentsrender

In React why does a child component's render function get called twice?


I have the simplest of apps. There's a parent <App> component and a child <MyChildOne> component. Both are class-based.

Can anyone please explain why React calls the render function of child <MyChildOne> twice?

Here's my <App> code:

import React from "react";
import "./App.css";
import MyChildOne from "./MyChildOne.js";

class App extends React.Component {
  render() {
    return (
      <div>
        <MyChildOne />
      </div>
    );
  }
}
export default App;

And here's my <MyChildOne> code:

import React from "react";

class MyChildOne extends React.Component {
  counter = 0;

  render() {
    this.counter = this.counter + 1;

    console.log(
      "Code has called MyChildOne and this.counter has value: " + this.counter
    );

    return <h1>Hello, {this.counter}</h1>;
  }
}

export default MyChildOne;

The output in the browser is this:

Hello, 1

And here's what gets logged in the console:

Code has called MyChildOne and this.counter has value: 1

Code has called MyChildOne and this.counter has value: 2

So clearly React is calling the render function of <MyChildOne> twice – but I cannot understand why!!!!

This is no good to me because I want to pass as props an array of things from <App> to <MyChildOne> and I want <MyChildOne> to render, let's say, an <h1> for every 'thing' member of that array. I do not want the <h1>s to be rendered twice!


Solution

    1. Your function is calling child render function a single times only.
    2. This is not the approach to create state in class component instead you can use.
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        };
    }
    
    1. The updation of state should be done using

      this.setState:

      {()=>{this.setState({ count:this.state.count+1 })}}

    2. The component that is rendering twice may be because of the event which you might be triggering like I was with my mouse-over event.