0

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 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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?
Basically the condition is if it is a function or a value. It is still a bit opinionated.
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.
Are you there @Julian
I think you want to add a function. Try const increment = useCallback(() => () => setC(c => c + delta),[delta])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.