burak unlu
burak unlu

Reputation: 193

react.js constructor called twice

I a have post list and I am trying to call an action inside of constructor or componentDidMount for each post. But somehow when I send a new message constructor and componentDidMount functions are called twice.

 constructor(props) {
    super(props);

    if (condition1) {
       this.props.actions.action1();
    } else if (condition2) {
       this.props.actions.action2();
    }    
}

These functions are called only once when the posts are readed from a list. But when I send a new message they are called twice.

How can i avoid these situation. I tried to use componendDidUpdate function like this:

componentDidUpdate(prevProps, prevState) {     
      if (prevProps.post.id !== this.props.post.id) {
         if (condition1) {
            this.props.actions.action1();
         } else if (condition2) {
            this.props.actions.action2();
         }
      }   
}

Upvotes: 14

Views: 13376

Answers (4)

Minwoo Yu
Minwoo Yu

Reputation: 500

I solved it with this

let onlyonce = false;

class PostPage extends React.Component {
    constructor(props) {
        super(props);

        this.struct()
    }
    async struct() {
        if(onlyonce) return;
        onlyonce = true;
//dom loading
    }
}

Upvotes: 0

Fredrik
Fredrik

Reputation: 5108

If you're not running StrictMode (if you are, see answer by papacool: it's by design), when the code in the constructor is run twice, you can be sure that the component is being created anew two times. This can happen of various reasons, the simplest reason is probably that the component is being used on multiple places:

<MyComponent />
<MyComponent />

Another reason could be that you have conditional rendering, meaning perhaps you're rendering based on a boolean, that changes:

{ myBoolean && <MyComponent /> }

If you toggle myBoolean two times, the constructor will be executed two times.

Upvotes: 2

papacool
papacool

Reputation: 452

React constructor is called twice in strict mode. https://stackoverflow.com/a/61443443/6014725

This is not a bug, but on purpose behavior to ensure that the constructor is pure. https://github.com/facebook/react/issues/12856#issuecomment-613145789

Learn more with https://reactjs.org/docs/strict-mode.html

Upvotes: 31

Dustin Gogoll
Dustin Gogoll

Reputation: 231

Well, when your constructor and your componentDidMount function both fire twice you can be sure that the component in question is constructed twice somewhere.

Upvotes: 2

Related Questions