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.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Rajat Sharma
  • 65
  • 1
  • 8

1 Answers1

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.

Julian Kleine
  • 1,539
  • 6
  • 14
  • 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? – Rajat Sharma Jan 15 '20 at 10:53
  • Basically the condition is if it is a function or a value. It is still a bit opinionated. – Julian Kleine Jan 15 '20 at 11:06
  • If I would like to replace the useCallback with useMemo in [this](https://github.com/sharmarajat01/useCallback/blob/master/src/pages/demo.js) , 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 Jan 15 '20 at 14:31
  • Are you there @Julian – Rajat Sharma Jan 17 '20 at 11:07
  • I think you want to add a function. Try `const increment = useCallback(() => () => setC(c => c + delta),[delta])` – Julian Kleine Jan 18 '20 at 20:59