简体   繁体   中英

How to use the react hook “useMemo” with asynchronous functions?

(CLOSED)

How can I await, to resolve/reject, the promise returned by a function wrapped in the react hook "useMemo"?

Currently, my code looks like this:

  // Get the persisted email/username
  const persistedUsername = useMemo(async () => {
    let username;

    try {
      username = await AsyncStorage.getData(`@${ASYNC_STORAGE_KEY}:username`);
    } catch {}

    return username;
  }, []);  

EDIT

What I am trying to achieve is to get the data before the component is rendered, some kind of "componentWillMount" life-cycle. My two options were:

  1. Computing the value using useMemo hook to avoid unnecessary recomputations.
  2. Combine useEffect + useState. Not the best idea because useEffect runs after the component paints.

@DennisVash has proposed the solution to this problem in the comments:

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 "paint" those changes.


As you can see, persistedUsername is still a promise (I am not waiting the result of the asynchronous function)...

Any ideas? Is it not a good idea to perform asynchronous jobs with this hook? Any custom hook?

Also, what are the disadvantages of performing this operation in this way compared to using useEffect and useState?

Same thing with useEffect and useState:

  useEffect(() => {
    // Get the persisted email/username
    (async () => {
      const persistedUsername = await AsyncStorage.getData(
        `@${ASYNC_STORAGE_KEY}:username`
      );

      emailOrUsernameInput.current.setText(persistedUsername);
    })();
  }, []);

Thank you.

Seems like the question is about how to use componentWillMount with hooks which is almost equivalent to useLayoutEffect (since componentWillMount is deprecated).

For more additional info, you should NOT resolve async action in useMemo since you will block the thread (and JS is single-threaded).

Meaning, you will wait until the promise will be resolved, and then it will continue with computing the component.

On other hand, async hooks like useEffect is a better option since it won't block it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM