title: React hooks without initial state
body: <p>I am working on a project where I am fetching some data from an API and storing it as a JSON object in a state hook. However, when initialised with <code>const [data, setData] = useState([])</code>, obviously, <code>data</code> stores an initial value of <code>[]</code> before fetchAPI passes in the correct values, which is causing all sorts of problems on the functionality because my functions cannot work on empty objects. </p>
  
  <p>I have tried sleep methods, async/await functions but it all comes down to me having to initialise that state. Components look like this:</p>
  
  <pre><code>// fetchHook.js
  
  import React, { useState, useEffect } from "react";
  
  function useFetch(url) {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
  
    async function fetchUrl() {
      const response = await fetch(url);
      const json = await response.json();
      setData(json);
      setLoading(false);
    }
  
    useEffect(() =&gt; {
      fetchUrl();
    }, []);
  
    return [data, loading];
  }
  
  export { useFetch };
  </code></pre>
  
  <p>and it is imported on main App component which then passes the <code>data</code> as users to another component like so:</p>
  
  <pre><code>// App.js
  import { useFetch } from "./components/fetchHook";
  
  
  function App() {
    const [users, loading] = useFetch("https://api.github.com/users");
  
    return (
      &lt;div className="App"&gt;
        &lt;Profiles users={users} count={count} /&gt;
      &lt;/div&gt;
    );
  }
  </code></pre>
  
  <p>How can I make sure that fetch method always returns valid data before returning the initial state?</p>