title: How to detect if state was changed? reactjs
body: <p>I have this code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>class App extends Component {
    constructor(props){
      super(props);
      this.state = {
        elements: [],
      }
    }
    loadData = () =&gt; {
      fetch('http://localhost:3001/')
      .then(res =&gt; res.json())
      .then(data =&gt; {this.setState({elements: data})})
      .catch(err =&gt; console.log(err))
    }
      newElement = () =&gt; {
      do {this.loadData()} while (/don't know what to put here/ === this.state.elements.length)
  
  
    componentDidMount(){
      this.loadData();
      console.log(this.state.feladatok)
  
    }
    render() {
      return (
        &lt;div className="App"&gt;
          &lt;Element newElem={() =&gt; this.newElement()}/&gt;
        &lt;/div&gt;
      );
    }
  }
  
  //The Element component renders more Element components. All element component looks like this inside:
  //&lt;Element newElem={this.props.newelem} /&gt;
  //If a new element has created, that will do two things:
  //Adds a new element to the database
  //The this.props.newElem() gets called</code></pre>
  </div>
  </div>
  </p>
  
  <p>The situation is that the newElement is called from the children component's props just if a new component was created (and posted to the database). I need to wait until the server responds with the new data. The data comes as an array. (approximately 10ms, but i think it's better to wait the time). The code shown above is my idea to detect if the elements length isn't the same it was before. But if i create a new state, for an example <code>elementsCounter</code>(and set the empty value to 0), whatever where i set it to <code>elements.length</code>, it still remains 0. Or if i declare a variable into the <code>newElement</code> function, and set the value to <code>this.state.elements.length</code>, and after do the <code>do...while</code>, it creates an infinite loop. So how to solve this problem?</p>