Search code examples
javascriptreactjsreact-lifecycle

ReactJS: Class Component Mounting Twice


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.


Solution

  • 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>
    );