Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs componentDidMount executes twice

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;```
like image 895
be well Avatar asked Jul 14 '26 17:07

be well


1 Answers

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 }));
}
like image 143
Nicholas Tower Avatar answered Jul 17 '26 21:07

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!