Does a callback in useMemo receive any arguments?
Asked Answered
P

2

17

I wonder if useMemo hook receives previous value for whatever it has memoized as any of the arguments to its callback?

Parent answered 27/3, 2019 at 8:38 Comment(0)
I
23

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

Insinuation answered 27/3, 2019 at 8:51 Comment(5)
It definitely should :/Parent
What do you expect to be there in useMemo callbackInsinuation
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 insteadThistly
E
5

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.

Eadmund answered 9/1, 2023 at 13:26 Comment(1)
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.