0

I have the following:

props = {
onPositive: () => void;
closeFunc: () => void;
... about 5 more props
}

With the following hook:

const onPositive: () => void = useCallback(() => {
        props.positionFunc();
        props.closeFunc();
    }, [props.positionFunc, props.closeFunc]);

I am getting this warning:

React Hook useCallback has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useCallback call and refer to those specific props inside useCallback 

From what I understand in DependencyList I should include the dependencies the callback has, am I missing something?

I can turn-off the warning by putting [props] for DependencyList however I don't think is needed?

Can somebody explain me why I should put props and not what I have?

0

2 Answers 2

2

The waring is pretty explicit about how to fix that:

However, 'props' will change when any prop changes, so the preferred fix is to destructure the 'props' object outside of the useCallback call and refer to those specific props inside useCallback

So the fix would be:

const {positionFunc, closeFunc} = props;

const onPositive: () => void = useCallback(() => {
       positionFunc();
       closeFunc();
    }, [positionFunc, closeFunc]);
0

This is expected behavior. the props itself is passed down so it may be possible to see stale value. Here is the reference to this information with clear explanation,

Here it the link to the response https://github.com/facebook/react/issues/16265#issuecomment-517518539

Screenshot for reference, enter image description here

PS: I couldn't provide all this info in a comment, as there is already an answer. However, I think it helps add more information and hence the additional answer.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.