I have some components that should do some work as soon as their data has arrived and rendered for the first time, but not for future rerenderings. For example: Comments are loaded and rendered, now 1. load social media libraries and 2. load some Google Analytics.
Right now I'm doing it like that:
componentDidUpdate: function (prevProps, prevState) {
    if (this.hasAlreadyUpdatedOnce) {
        // ... do some stuff...
    } else {
        // ... do some stuff that should happen only once...
        // 1. load social media libraries
        // 2. load some Google Analytics
        this.hasAlreadyUpdatedOnce = true;
    }
}
But I'm asking myself if there's a more elegant way than setting a property like that.
Assuming you're responding to a state change, you should pass a callback as the second argument to setState.
componentDidMount: function(){
  ajaxyThing(function(data){
    this.setState({data: data}, function(){
      // this.state is updated, the component has rerendered 
      // and the dom is current
    });
  }.bind(this));
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With