Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  163] [ 5]  / answers: 1 / hits: 7696  / 4 Years ago, sun, december 13, 2020, 12:00:00

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.


More From » reactjs

 Answers
14

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.


[#2134] Monday, December 7, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
samir

Total Points: 145
Total Questions: 90
Total Answers: 89

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;