0

I want to dispatch some action when my React component unmounts. As I am using hooks, I can't use componentWillUnmount. Instead, I am using the useEffect hook:

const dispatch = useDispatch();
useEffect(() => () => dispatch(setValue()), []);

Above code throws the warning "React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array". I can't include dispatch in dependencies array as it will cause useEffect to run whenever dispatch changes, but I want it to run only when the component is unmounting; and for that I need to pass an empty array.

How can I fix this warning without removing the corresponding linting rule from babel?

darKnight
  • 5,651
  • 13
  • 47
  • 87
  • Possible duplicate of [How to fix missing dependency warning when using useEffect React Hook?](https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook/55854902#55854902) – Shubham Khatri May 08 '20 at 07:18

1 Answers1

1

dispatch should not change, it's the dispatch function provided from the redux store. The react hook linter just sees it as a function, however, and is warning you it can be mutated. I think you've a syntax error though, missing parens. I think it should be

useEffect(() => () => dispatch(setValue()), []);

You can ignore the rule for that line though, if necessary

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

Usage

// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => () => dispatch(setValue()), []);

or (IMO a bit easier to read)

useEffect(() => {
  return () => dispatch(setValue());
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181