title: ReactJS: Empty component's old fetched data before fetching again
body: <p>I am fetching remote data from my React component. When data is ready, child components are rendered. While data is loading, the 'Data is loading ....' text is displayed.</p>
  
  <p>When the component is rendered for the second time due to the <code>props</code> change, I set the previous data to <code>null</code> in order to show that new data is loading.</p>
  
  <pre><code>const List = (props) =&gt; {
    const [items, setItems] = useState(null);
  
    useEffect(() =&gt; {  
      setItems(null);
  
      fetch(`http://some_url_to_fetch_items.com?PAGE=${props.page}`)
      .then((data) =&gt; {
         setItems(data);
      })   
    }, [props.page]);
  
    if (!items) {
      return "Data is loading ......."
    }
  
    return (
      &lt;ul&gt;
        {items.map(item =&gt; (
          &lt;li&gt;{item}&lt;/li&gt;
        ))}
      &lt;/ul&gt;
    )
  }
  </code></pre>
  
  <p>The problem of this approach is that when the component is rendered for the second time the <code>setItems(null);</code> code is not executed immediately (probably because <code>useEffect</code> is executed asynchronously) and the component re-renderes 3 times instead of expected 2:</p>
  
  <ul>
  <li>1-st re-render because of the props change (BUT with old data, since <code>setItems(null)</code> is executed too late)</li>
  <li>2-nd re-render after <code>setItems(null)</code> is finally executed</li>
  <li>3-rd re-render after data is fetched</li>
  </ul>
  
  <p>I understand what the problem with my approach is. But I don't see another way. 
  It is mandatory to use hooks.</p>
  
  <p>Any ideas?</p>