最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use the react hook "useMemo" with asynchronous functions? - Stack Overflow

programmeradmin0浏览0评论

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 ponent is rendered, some kind of "ponentWillMount" life-cycle. My two options were:

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

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

Blocking all the visual effects using the useLayoutEffect hook (some kind of ponentDidMount/ponentDidUpdate) 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 pared 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.

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 ponent is rendered, some kind of "ponentWillMount" life-cycle. My two options were:

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

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

Blocking all the visual effects using the useLayoutEffect hook (some kind of ponentDidMount/ponentDidUpdate) 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 pared 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.

Share Improve this question edited Dec 23, 2021 at 12:59 Mir-Ismaili 17.2k8 gold badges101 silver badges120 bronze badges asked Dec 13, 2020 at 11:43 Victor MolinaVictor Molina 2,6613 gold badges28 silver badges59 bronze badges 9
  • So declare a promise inside the useMemo and call it?... – Dennis Vash Commented Dec 13, 2020 at 11:53
  • seems to me more of a usecase for useEffect and useState instead – thedude Commented Dec 13, 2020 at 11:56
  • @thedude Yes, I also thought the same, but maybe it is possible to do this with useMemo (I have never used it for asynchronous operations). – Victor Molina Commented Dec 13, 2020 at 11:59
  • Do you know the differences between useEffect and useMemo? They do not serve the same purpose, why would you make an async action in useMemo? Are you basically asking what is the difference between them? – Dennis Vash Commented Dec 13, 2020 at 12:35
  • @DennisVash useEffect is to perform actions after the rendering, the last execution of the ponent, right? And useMemo to perform weight actions, avoiding re-puting them in each render. – Victor Molina Commented Dec 13, 2020 at 12:48
 |  Show 4 more ments

1 Answer 1

Reset to default 6

Seems like the question is about how to use ponentWillMount with hooks which is almost equivalent to useLayoutEffect (since ponentWillMount 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 puting the ponent.

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

发布评论

评论列表(0)

  1. 暂无评论