3
votes

I am rendering a simple react component, where no state and props are set

I am logging text to console only once inside the render function but it's logged twice:

rendering counter
rendering counter

Below is the code of the component counter.js

import React, { Component } from "react";

class Counter extends Component {
  render() {
    console.log("rendering counter");       //this is printed two times

    return <span className={"badge m-3 badge-primary"}>counter</span>;
  }
}
export default Counter;

And index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.css";
import Counter from "./components/counter";

ReactDOM.render(
  <React.StrictMode>
    <Counter />
  </React.StrictMode>,
  document.getElementById("root")
);
serviceWorker.unregister();

it seems that the render function in the component is called two times. But why is that?

1

1 Answers

5
votes

As it was written in docs:

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following methods:

  • Class component constructor method
  • The render method
  • setState updater functions (the first argument)
  • The static getDerivedStateFromProps lifecycle
  • The shouldComponentUpdate method