React class component rendering twice

Viewed 227

I have created a class component as in the code.

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import Home from "./components/home";

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

serviceWorker.unregister();

home.jsx

import React, { Component } from "react";

class Home extends Component {
  state = {};

  render() {
    console.log("Render Home");
    return <h1>Home</h1>;
  }
}

export default Home;

If I change it the Home to a functional component then it render only once. But why is class component rendering twice?

2 Answers

The answer lies in the React docs regarding Strict Mode:

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 functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

Fortunately, this only applies to development mode, so you won't have this double-rendering in production.

Try without strict mode:

ReactDOM.render(
  <Home />,
  document.getElementById("root")
);
Related