I am learning the hooks in ReactJs and stuck to some kind of warnings like dependencies. Here in src/pages/home, I am using useCallback in it. And One more question, Could you please give me real life condition where I need to use useCallback and useMemo, in my project in future. Means, When I should go for useMemo and when to go for useCallback.Thanks.
1 Answer
You need to provide a dependency array as second parameter. Please refer to the official React docs for hooks
As a code example
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
please note the second parameter of useCallback, the dependency array.
In general useMemo is used for memoized values and by convention useCallback is used for memoized functions. They are very similar.
5 Comments
Rajat Sharma
Hey @Julian thanks for the answer, i already got that dependency array's solution but the main concern is, when i will need to memoized any value or function? Any condition can you elaborate?
Julian Kleine
Basically the condition is if it is a function or a value. It is still a bit opinionated.
Rajat Sharma
If I would like to replace the useCallback with useMemo in this , like replace this -
const increment = useCallback(() => setC(c => c + delta),[delta]) with const increment = useMemo(() => setC(c => c + delta),[delta]) then it is not working as expected. And in the dependency array, i wrote delta which is a value not a function.Rajat Sharma
Are you there @Julian
Julian Kleine
I think you want to add a function. Try
const increment = useCallback(() => () => setC(c => c + delta),[delta])