title: 'if else statement' doesn't work properly when importing data as props in React
body: <p><code>if else</code> statement inside <code>useEffect</code> doesn't work as expected. <code>else</code> is executed before the code inside the <code>if</code> is executed completely. I've commented out what I'm expecting in the code. <code>someData</code> prop is the data fetched from the server using the <code>fetch API</code> in the parent component.</p>
  <pre><code>import { useState, useEffect } from &quot;react&quot;;
  
  const App = ({ someData }) =&gt; {
    const [text, setText] = useState(0)
    const [lastNumber, setLastNumber] = useState(0)
    useEffect(() =&gt; {
      if (!someData) {
        (async () =&gt; {
          const res = await fetch(`https://xxx-xxx......`);
          const myJson = await res.json();
          const _lastNumber = myJson.number // 1000
          setLastNumber(_lastNumber)
          console.log(lastNumber) // 1000, appear in the console second
        })();
      } else {
          console.log(lastNumber) // 0, appear in the console first
          setText(
            lastNumber - someData.number // 0 - 100 (I expect &quot;1000 - 100&quot;.)
          );
      }
    }, [someData, lastNumber]);
  
    if (!someData) {
      return (
        &lt;div&gt;
          &lt;h1&gt;Loading&lt;/h1&gt;
        &lt;/div&gt;
      )
    } else {
      return (
        &lt;div&gt;
          &lt;h1&gt;{text /* -100 (I expect &quot;900&quot;.) */}&lt;/h1&gt;
        &lt;/div&gt;
      );
    }
  };
  
  export default App;
  </code></pre>
  <p>If I write code like this using some tricks, it takes a long time to load but works as I want.</p>
  <pre><code>import { useState, useEffect } from &quot;react&quot;;
  
  const App = ({ someData }) =&gt; {
    const [text, setText] = useState(0)
    const [lastNumber, setLastNumber] = useState(0)
    useEffect(() =&gt; {
      if (!someData) {
        (async () =&gt; {
          const res = await fetch(`https://xxx-xxx......`);
          const myJson = await res.json();
          const _lastNumber = myJson.number // 1000
          setLastNumber(_lastNumber)
          console.log(lastNumber)
        })();
      } else {
        if (lastNumber !== 0) {
          console.log(lastNumber) 
          setText(
            lastNumber - someData.number
          );
        }
      }
    }, [someData, lastNumber]);
  
    if (!someData) {
      return (
        &lt;div&gt;
          &lt;h1&gt;Loading&lt;/h1&gt;
        &lt;/div&gt;
      )
    } else {
      return (
        &lt;div&gt;
          &lt;h1&gt;{text /* 900 */}&lt;/h1&gt;
        &lt;/div&gt;
      );
    }
  };
  
  export default App;
  </code></pre>
  <p>But I don't know why it works the way that I want and if it's a good way to do it. Please let me know the better way.</p>