简体   繁体   中英

Is secure to ignore the missing dependencies es-lint warning on react hooks?

I have a component which needs to call a function when is unmounted. This function is passed as a prop of the component. As far as I know, to call a function on component unmount you only need a useEffect with an empty dependency array:

useEffect(() => {
    return () => { prop.onUnmount() }

}, []);

This works as expected, however ESLint complains about a missing dependency on the hook:

Line 156:6: React Hook useEffect has missing dependencies: 'props.onUnmount'. Either include them or remove the dependency array react-hooks/exhaustive-deps

However, neither solutions works,

  • If I remove the dependency array, the hook will be executed on each re render
  • If add the dependency, despite of prop.onUnmount() does not change on any rerender and the hook should not be triggered, it stills executing the return part. So the function gets called before the unmount.

So, is it safe to ignore the warning or is there any work around to execute the function and prevent ESLint to warn about it?

useEffect(() => {
    return () => { prop.onUnmount() }
}, []);

This will run the prop.onUnmount function that existed on the very first render. So if that prop changes during the life of the component, your code will ignore that change, which is what the lint rule is warning you about.

If you want to run the prop.onUnmount that exists on the last render, then you'll need to do the following:

const cleanup = useRef();
// update the ref each render so if it changes the newest
//   one will be used during unmount
cleanup.current = prop.onUnmount;
useEffect(() => {
  return () => {
    cleanup.current();
  }
}, []);

If you find yourself doing this a lot, you may want to extract it to a custom hook, as in:

export const useUnmount = (fn) => {
  const fnRef = useRef();
  fnRef.current = fn;
  useEffect(() => {
    return () => {
      fnRef.current();
    }
  }, []);
};

// used like: 
useUnmount(props.onUnmount);

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