I wonder if useMemo
hook receives previous value for whatever it has memoized as any of the arguments to its callback?
Does a callback in useMemo receive any arguments?
Asked Answered
Does a callback in useMemo receive any arguments?
No, The callback to useMemo
doesn't receive any arguments. It just relies on the array passed as second argument to execute the callback and return any result returned after executing the callback.
You can find a demonstration of this in codesandbox here
It definitely should :/ –
Parent
What do you expect to be there in useMemo callback –
Insinuation
Previous values. –
Parent
If you are looking for previous input values or previous result value. In any case the idea of memoization is based on pure function so that the result only depends on the arguments and nothing else which is why you don't see any arguments in useMemo. –
Insinuation
how about using useCallback instead –
Thistly
To be able to pass arguments, you should be using React's useCallback(fn, dependencies)
hook instead.
useCallback
is a React Hook that lets you cache a function definition between re-renders, so it's perfect for your use case.
So, I definitely agree with @mahmoudafer 's answer:
how about using useCallback instead
I couldn't comment or upvote because of reputation limitations.
I think the question was about if
useMemo
recieves previous value as an argument in the callback. The useCallback
hook is similar to the useMemo
but works in a different way. The useMemo
executes the provided callback after its dependencies were changed and stores its output until the denendencies are changed again, but the function provided to useCallback
is not called. The function you provide to useCallback
is memoized everytime the dependencies change and returned as it is. This means that you can't get the previous value either. –
Vaules © 2022 - 2024 — McMap. All rights reserved.