Home > Blockchain >  React Hook useEffect has a missing dependendency
React Hook useEffect has a missing dependendency

Time:03-24

I am developing a react JS website to assist TFserving

in my file home.js there is an error in the following line

  useEffect(() => {
    if (!preview) {
      return;
    }
    setIsloading(true);
    sendFile();
  }, [preview]);

Error message:-

React Hook useEffect has a missing dependency: 'sendFile'. Either include it or remove the dependency array.

CodePudding user response:

It is showing you the warning because you are using sendFile() method and you didn't add it to the dependency array. So you have two options.

1.) Add it to the dependency array

 useEffect(() => {
    if (!preview) {
      return;
    }
    setIsloading(true);
    sendFile();
  }, [preview, sendFile]);

2.) use eslint-disable-next-line By using this, It won't show the warning anymore.

  useEffect(() => {
    if (!preview) {
      return;
    }
    setIsloading(true);
    sendFile();
    //eslint-disable-next-line
  }, [preview]);

CodePudding user response:

If you want the effect to run only when preview changes then it is technically correct to specify just preview to dependency array. But, the React-hooks linting rules aren't able to differentiate this case. You can disable the rule specifically for that line with:

// eslint-disable-next-line react-hooks/exhaustive-deps

but better is using useCallback:

const sendFile= useCallback(() => {
  
}, [])

here, if you have dependencies in your function, you will have to include them in the useCallback dependencies array and this will trigger the useEffect again if the functions parameters changes.

  • Related