2

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;```
be well
  • 325
  • 2
  • 14
  • 3
    `React.StrictMode`? https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors – jonrsharpe Apr 05 '22 at 16:13
  • If you're using the latest React version you should remove `componentDidMount` and use hooks instead. – 0stone0 Apr 05 '22 at 16:23
  • You can read this too... https://stackoverflow.com/questions/48846289/why-is-my-react-component-is-rendering-twice – mc-user Apr 05 '22 at 16:25

2 Answers2

3

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 }));
}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
0

better try with function component like :

useEffect (() => {
//core work

},[]);
AMRIT SHAHI
  • 71
  • 1
  • 8
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 05 '22 at 19:38