简体   繁体   中英

Best practice: React useEffect hook dependencies when setting loading state

I'm learning React hooks and am struggling with linting rules around exhaustive deps. In particular, I want to set a status of "loading" when an API call is being made (showing a loading message to the user, for example), then set it to "idle" when the call is returned, but the linter says there are missing dependencies. Here's the hook:

useEffect(() => {
    setStatus(STATUSES.LOADING);
    getData()
      .then(result => {
        setStatus(STATUSES.IDLE);
        setData(result);
      });
  }, []);

According to the linter, I should be adding dependencies for STATUSES.LOADING and STATUSES.IDLE - this seems counterintuitive though, as I don't want to arbitrarily re-run the API call whenever the status is changed.

I don't want to just ignore the warning, so is there a better pattern here to achieve what I want to do?

The linting rule does not know whether the dependencies are going to change or not. It is there to avoid unexpected bugs in future like if the value is being provided from parent component and can change there.

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