Ram Kc
Ram Kc

Reputation: 13

React Component mounting life cycle called twice react 16.13.1

I am using react 16.13.1 and created react app using create-react-app 3.4.1.

Mounting lifecycle is being called twice for every component.

I created component FirstComponent.js

import React, {Component} from 'react';

class FirstComponent extends Component {
    constructor(p) {
        super(p);
        console.log("FirstComponent constructor called")
    }

    componentDidMount() {
        console.log("FirstComponent componentDidMount called")
    }

    static getDerivedStateFromProps() {
        console.log("FirstComponent getDerivedStateFromProps called")
        return null;
    }

    render() {
        console.log("FirstComponent render called")
        return (
            <div>
                Hello World
            </div>
        );
    }
}
export default FirstComponent;

and called FirstComponent from App.js

import React, {useEffect} from 'react';
import FirstComponent from "./FirstComponent";

function App() {
  useEffect(()=>console.log("App useEffect Called"));

  console.log("App called");
  return (
    <FirstComponent/>
  );
}
export default App;

console output: (ignoring getDerivedStateFromProps warning)

App called
App called
FirstComponent constructor called
FirstComponent constructor called
FirstComponent getDerivedStateFromProps called
FirstComponent getDerivedStateFromProps called
FirstComponent render called
FirstComponent render called
FirstComponent componentDidMount called
App useEffect Called

Upvotes: 1

Views: 755

Answers (1)

rzwnahmd
rzwnahmd

Reputation: 1082

This is because codesandbox.io runs react applications in strict mode by using <React.StrictMode /> and in strict mode side effects are double-invoked means executed two times, if you unwrap your <App /> component from <React.StrictMode> in index.js it'll work just fine.

Here's how docs define this:

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

Class component constructor, render, and shouldComponentUpdate methods Class component static getDerivedStateFromProps method Function component bodies State updater functions (the first argument to setState) Functions passed to useState, useMemo, or useReducer

Upvotes: 5

Related Questions