简体   繁体   中英

React hooks appends unwanted value with eslint-plugin-react-hooks@next

I have a useEffect hook in my component which call a Redux action to fetch some data.

useEffect(
 () => {
   props.getClientSummaryAction();
  },[]
);

When I go to save the file the linter does this.

useEffect(
  () => {
    props.getClientSummaryAction();
 }, [props] 
);

Which obviously send my component into an infinite loop as getClientSummaryAction fetches some data which updates the props.

I have used deconstruction like this and the linter updates the array.

  const { getClientSummaryAction } = props;

  useEffect(
    () => {
      getClientSummaryAction();
    },
    [getClientSummaryAction]
  );

Which I am fine with but it doesn't really make sense because getClientSummaryAction will obviously never be updated, its a function.

I just want to know why the linter is doing this and whether this is best practice.

It's not unwanted. You know for a fact that the dependency is not going to change, but React can possibly know that. The rule is pretty clear:

Either pass an array containing all dependencies or don't pass anything to the second argument and let React keep track of changes.

Pass the second argument to useEffect is to tell React that you are in charge of hook's call. So when you don't pass a dependency that is included inside your effect eslint will see this as a possible memory leak and will warn you. DO NOT disable the rule just continue to pass the dependency as you are already doing. May feel redundant but it's for the best.

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