title: How to use the react hook "useMemo" with asynchronous functions?
body: <p>How can I await, to resolve/reject, the promise returned by a function wrapped in the react hook &quot;useMemo&quot;?</p>
  <p>Currently, my code looks like this:</p>
  <pre><code>  // Get the persisted email/username
    const persistedUsername = useMemo(async () =&gt; {
      let username;
  
      try {
        username = await AsyncStorage.getData(`@${ASYNC_STORAGE_KEY}:username`);
      } catch {}
  
      return username;
    }, []);  
  </code></pre>
  <hr />
  <h2>EDIT</h2>
  <p>What I am trying to achieve is to get the data before the component is rendered, some kind of &quot;componentWillMount&quot; life-cycle. My two options were:</p>
  <ol>
  <li>Computing the value using useMemo hook to avoid unnecessary recomputations.</li>
  <li>Combine useEffect + useState. Not the best idea because useEffect runs after the component paints.</li>
  </ol>
  <p>@DennisVash has proposed the solution to this problem in the comments:</p>
  <p>Blocking all the visual effects using the useLayoutEffect hook (some kind of componentDidMount/componentDidUpdate) where the code runs immediately after the DOM has been updated, but before the browser has had a chance to &quot;paint&quot; those changes.</p>
  <hr />
  <p>As you can see, persistedUsername is still a promise (I am not waiting the result of the asynchronous function)...</p>
  <p>Any ideas? Is it not a good idea to perform asynchronous jobs with this hook? Any custom hook?</p>
  <p>Also, what are the disadvantages of performing this operation in this way compared to using useEffect and useState?</p>
  <p>Same thing with useEffect and useState:</p>
  <pre><code>  useEffect(() =&gt; {
      // Get the persisted email/username
      (async () =&gt; {
        const persistedUsername = await AsyncStorage.getData(
          `@${ASYNC_STORAGE_KEY}:username`
        );
  
        emailOrUsernameInput.current.setText(persistedUsername);
      })();
    }, []);
  </code></pre>
  <p>Thank you.</p>