3

I want to use useEffect to fire 2 functions (which are redux actions creators) - one function when component mounts, and the other one on unmount, like so:

// ...

function MyComp(props) {
  function handleSelectItem(itemId) {
    const data = props.data.filter(/* some filter logic depending on itemId */);
    props.selectItem({ itemId, data });
  }

  useEffect(() => {
    handleSelectItem(1);
    return props.deselectItem;
  }, []);
}

export default connect(null, {selectItem, deselectItem})(MyComp)

It works, but the react-hooks/exhaustive-deps eslint rule telling me that my useEffect has 2 dependencies which I should include into the dependencies array (useEffect's second argument) or remove the array completely. Second option is not suitable as I don't need these functions to be called on each render. Hence, I need to include them both. There is an article regarding including functions into dependency array. Things described there is pretty much clear to me, but I still confused about the redux action creators in dependencies array and how react will shallowly compare this functions. For me this is a little bit hard to understand. What is the right way to resolve this particular case what is the right way to use redux action creators in useEffect in general?

mcmxc
  • 574
  • 1
  • 7
  • 19
  • Possible Duplicate of [How do I fix missing dependency in React Hook useEffect](https://stackoverflow.com/questions/55840294/how-do-i-fix-missing-dependency-in-react-hook-useeffect/55854902#55854902) – Shubham Khatri May 16 '19 at 14:05
  • Do you need to use `handleSelectItem` not only in `useEffect`? If not, @ShubhamKhatri gives you a link with the answer. If you need to use `handleSelectItem` in other places, I will write an answer. – Andrii Golubenko May 16 '19 at 16:00
  • @AndriiGolubenko in my case, `handleSelectItem` is a click event handler. It will execute on each item click (with item id parameter passed in). But also I need to have this event handler fired when component mounts, with a particular `itemId` as a parameter. Answering you question - yes, I need to use it in other places. – mcmxc May 16 '19 at 19:53

0 Answers0