React.Component class constructor runs once without console.log?

Viewed 172

This React.Component class constructor seems to be run 2 times for one instance, in a weird way.

Apparently:

  1. the counter is incremented 0 -> 1 without a console.log output
  2. the counter is incremented 1 -> 2 with a console.log output

Is this true ? Why does the console show 2 and not 1 ?

import React from 'react';

var instanceCount = 0;
console.log('root:', instanceCount);

class App extends React.Component {

    constructor(props) {
        super(props);
        console.log('before change:', instanceCount);
        instanceCount++;
        console.log('after change:', instanceCount);
    }

    render() {
        return (
            <>test</>
        );
    }
}

export default App;

// console output:
//   root: 0
//   before change: 1
//   after change: 2

In contrast, a "normal" javascript class behaves as expected:

var instanceCount = 0;
class SomeClass {
    constructor(props) {
        console.log('before change:', instanceCount);
        instanceCount++;
        console.log('after change:', instanceCount);
    }
}
var instance = new SomeClass();

// console output:
//   before change: 0
//   after change: 1
1 Answers

It happens because you are using StrictMode:

... This is done by intentionally double-invoking the following functions:

Class component: constructor ...

The mode invokes the constructor twice, and React also silences the log:

Starting with React 17, React automatically modifies the console methods like console.log() to silence the logs in the second call to lifecycle functions. ...

// Remove StrictMode
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);

Edit nostalgic-currying-cn7ht

Related