To specify or not specify all useEffect dependencies

Viewed 54

I've created this useEffect construct to first launch validation and then to POST the data if it passes validation:

  const isFirstRun = useRef(true);

  useEffect(() => {
    if (isFirstRun.current) {
      isFirstRun.current = false;
      return;
    }

    if (isProcessing) {
      validate();
    } else {
      if (_.isEmpty(validationErrors)) {
        console.log('*** Ready to POST ***');

      }  
    }
  }, [isProcessing]);

I'm entirely fine with having just isProcessing as the only dependency for the useEffect but the VSCode linter is insisting that validate and validationErrors also be included.

I'm sure that adding validate would cause no problems but given that the validation code keeps adding items to validationErrors, I don't want this useEffect triggered every time it's changed.

How would you handle this situation?

1 Answers

Just becuase VSCode linter is suggesting it dosent make it best practice to follow. You my friend is doing just fine by only triggering useEffect only and only when you require, in your case when isProcessing changes, this is perfect way to optimize and reduce load on application processing.

Your case 1 : Adding validate

You are somehow correct as function reference is not changing so it wont trigger useEffect

Your case 2 : Adding validationErrors

This could be a big issue if your validate function modifies validationErrors as it will create a big chain of validationErrors modification which will result in calling useEffect infinitely in some specific cases.

So yes you can ignore those suggestion. useEffect is a really great thing but one should be careful while handling it. :-)

Related