0

I'm having a function object wrapped inside an useCallback statement which needs to invoke a function that is being injected via props:

const update = useCallback(() => {
    /*some stuff*/
    props.OnUpdate();
}, [..other_args, props.OnUpdate]);

useEffect(() => {
    update();
}, [args]);

Which leads to an infinite loop. If I remove props.OnUpdate from the dependencies array, the build is showing a warning that OnUpdate needs to be present in the dependencies array (or pass an empty array).

If I don't use useCallback, I end up with another warning: The 'update' function makes the dependencies of useEffect Hook (at line XY) change on every render. To fix this, wrap the definition of 'update' in its own useCallback() Hook

EDIT Here's the code of the OnUpdate which gets injected:

const callback = useCallback(() => {
    update({
        command: props.Command,
        target: props.Target
    });
}, [props.Command, props.Target, update])

Where update comes from a custom hook, which works correctly

bob_saginowski
  • 1,429
  • 2
  • 20
  • 35
  • 1
    Can you share the code for `OnUpdate`? You probably need to memoize it as well using `useCallback`, as it might result in `update` changing on every render. – Houssam Oct 19 '21 at 14:22
  • What are `args` and `other_args`, and _some stuff_? Those are important to make this code reproducible. – Sinan Yaman Oct 19 '21 at 14:23

0 Answers0