3

I am new to react and what to understand why the console.log is called twice when inside of the render function ?

import React, { Component } from "react";
import "./App.css";

class App extends Component {

  render() {
    console.log("Prints twice in console");
    return (
      <div className="App">

      </div>
    );
  }
}

export default App;

Where as if i dont extend from component and use function instead the console prints only once

import React from "react";
import "./App.css";
function App() {
  console.log("prints once");
  return <div className="App"></div>;
}

export default App;
  • I might add this is not the best way to debug an app. The React itself might rerender your component whenever it see it fit – user0101 Jul 10 '20 at 12:29
  • 1
    In this article somebody talks in depth about the double rendering: https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/ – dejoma Jul 10 '20 at 12:32
  • thanks dejoma - the article helped. – user1738360 Jul 11 '20 at 13:10

1 Answers1

1

Check your index.js in the ./src directory. I think it renders the App component in

<React.StrictMode>

Remove it and it will stop rendering the function twice.

Also you can check This

Arnab
  • 936
  • 7
  • 13