0

I am rendering a class component Rates within the functional component of App.js.

When the page is loaded, the componentDidMount function is being called twice.

Here is App.js:

import './App.css';
import Rates from './views/Rates';

function App() {
  

  return (
    <div className="App">
      <header className="App-header">
        <div className="header-container">
          <div style={{width: '33%'}}></div>
          <div style={{width: '33%'}}><h2>Farmr</h2></div>
          <div style={{width: '33%'}} className="account-section">
            <button className='btn' type='button'>Sign In</button>
          </div>
        </div>
        <div className="toolbox-container">
          <ul className="toolbar">
            <li>List One</li>
            <li>List Two</li>
            <li>List Three</li>
          </ul>
        </div>
      </header>
      <div className="main-body">
        <Rates/>
      </div>
    </div>
  );
}

export default App;

And here is Rates.js:

import React from "react";
import axios from "axios";

class Rates extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            rates: []
        };
    }

    componentDidMount() {
        console.log('mount');
    }

    render() {
        return (
            <div>
                <div>Rates</div>
            </div>
        );
    }
}

export default Rates;

There is no conditional rendering of the component so I'm not sure where the duplicate call is coming from.

MattArgo
  • 21
  • 5
  • If you're using strict mode and React 18, this is expected behavior. It only happens in development mode and should not affect your app. – Guillaume Brunerie Apr 24 '22 at 21:51
  • Yes that was it, I didn't know about this - I'm surprised I never came across this issue in the past. Thanks! – MattArgo Apr 24 '22 at 22:03

1 Answers1

0

The issue here was React rendering in StrictMode when in development.

The issue can be resolved by removing the StrictMode tags within index.js:

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
MattArgo
  • 21
  • 5
  • Well, it is not a bug, it is a feature. You should not remove strict mode, you should instead design your components in a way that it's not a problem if they get sometimes unmounted and then mounted again. – Guillaume Brunerie Apr 24 '22 at 22:07