简体   繁体   中英

React Hook useCallback has a missing dependency warning, but the dependencies are present

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?

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]);

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, 在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM