Reputation: 1
In my component Constructor and render method are called twice. I created a brand new project from create-react-app, it only one component other than App component so it is not so complex and complicated but still the problem persists.
import React from "react";
import logo from "./logo.svg";
import "./App.css";
import First from "./First";
function App() {
return (
<div className="App">
<First />
</div>
);
}
export default App;
import React, { Component } from "react";
class First extends Component {
static count = 0;
constructor(props) {
super(props);
this.state = {};
console.log("ctor");
alert("ctor");
}
render() {
First.count++;
console.log("Render method", First.count);
return <div>Hello World</div>;
}
}
export default First;
All other lifecycle hooks are being rendered once, no issues with them.
Upvotes: 0
Views: 825
Reputation: 525
it's probably because of React StrictMode in your index.js file.
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
strict mode checks for potential problems and it caused to run some lifecycle methods (like constructor, render, componentShouldUpdate, etc) twice. if it bugs you, you can simply remove it but better to don't.
Strict mode checks are run in development mode only; they do not impact the production build.
you can read more about it on strict-mode
Upvotes: 1
Reputation: 51
your code is just fine Constructor and render method are called only once i have tried in my machine.
Upvotes: 0