Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js - componentWillReceiveProps being hit twice

I have a React.js component that's being rendered like so:

    <Social email={this.state.email} />;

There are some events on the page that update this.state.email, and as a result, go through render, which sends a new email prop to the Social component.

In this Social component, I'm listening for updates like so:

  componentWillReceiveProps: function(nextProps) {
    console.log('received props update', nextProps.email);
    this.doSomeWork();
  }

That console line is being rendered twice which makes the UI flash twice along with calls to social networks.

I could always do something like:

    if (nextProps.email != this.props.email) {
      this.doSomeWork();
    }

But it felt a little hacky...

Is the double message expected? and if so, curious why?

If not, what's the best way to both track down and eliminate it?

like image 561
brandonhilkert Avatar asked Dec 23 '14 21:12

brandonhilkert


1 Answers

Your Social component is probably being rendered twice because setState is called twice on the parent component. It may be setting properties other than email but your render function is called so the Social component renders twice.

You can implement shouldComponentUpdate method in the Social component to prevent second rendering:

shouldComponentUpdate: function(nextProps, nextState) {
    return nextProps.email != this.props.email;
}
like image 185
nilgun Avatar answered Oct 14 '22 00:10

nilgun