I am studying ReactJs and faced some issues. My problem is that I have a simple app using latest ReactJs (v 18.0.0) and componentDidMount executes twice. Why?
index.js
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
monsters: []
};
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => this.setState({ monsters: users }));
}
render() {
return (
<div className="App">
{this.state.monsters.map(monster =>
<h1 key={monster.id}>{monster.name}</h1>
)}
</div>
);
}
}
export default App;```
CodePudding user response:
In React version 18, a change was made to strict mode so that components will mount, then unmount, then mount again. This was added to help us all start catching issues that will affect an upcoming feature. In a future version of react, state will be able to be preserved between unmounts, and as a result, components may mount multiple times.
For the most part, you can just ignore the double mount right now. But if you like, you could start writing code for the future, so your component checks whether it has already mounted before and skips the fetch:
componentDidMount() {
if (this.fetchPromise) {
// already mounted previously
return;
}
this.fetchPromise = fetch('https://jsonplaceholder.typicode.com/users'
.then(response => response.json())
.then(users => this.setState({ monsters: users }));
}
CodePudding user response:
better try with function component like :
useEffect (() => {
//core work
},[]);