3

React docs example shows only [a, b] as dependencies. Function doSomething is not passed.

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],
);

But later docs reads:

every value referenced inside the callback should also appear in the dependencies array.

My question: do I need to pass doSomething as well?

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b, doSomething],
);
2
  • 2
    How is doSomething defined? Can it ever change? Commented Dec 19, 2019 at 21:19
  • 2
    if doSomething is defined within the component or custom hook, or is passed as a parameter, then yes. If it's defined outside the function scope, then no. Commented Dec 19, 2019 at 21:35

1 Answer 1

4

Technically it's not required if it doesn't change, but it can bring unexpected behavior, so just for simplicity you need to pass all things you used inside if it's declared in component or comes from props. Also if you are using eslint, there is awesome plugin for hooks which is de-facto standard

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

Comments

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.