from Hacker News

Lead says async func in useCallback is incorrect, use useMemo instead, WTF?

by sakerbos on 9/18/23, 5:53 AM with 3 comments

Hello hackers! Normally I would discuss this with the team but it's just me and our Tech Lead on the FE so I'm posting here for my own educational purposes.

I submitted a PR review containing an async function in a React useCallback earlier and our tech lead mentioned that:

"You can't async useCallback, it can cause unexpected behavior. To achieve a memoised async function instead use useMemo".

It was always my understanding that useCallback returned a memoised function and useMemo a memoised result or am I missing something here?

The asynchronicity should also be irrelevant or?

Any feedback would be appreciated, thanks!

  • by acemarke on 9/18/23, 4:25 PM

    You can memoize any function with `useCallback`, sync or async. All it's doing is watching when the deps array changes, and saving whatever function reference was passed in at that time.

    (Note that this does not mean that the function itself is memoized in terms of "cache the result and check the arguments to see if we know this answer already".)

  • by theGeatZhopa on 9/18/23, 6:10 AM

    Just try it out. The programming language of your choice sure offers information and tools.