Search code examples
javascriptreactjsreact-hooksuse-effect

useEffect dependency only if a certain variable is present then only watch it as dependency


I have the following set of running code:

useEffect(() => {
 if (field[1].isActive === true) {
  handleMore();
 }
}, [field[1].text]);

The issue is sometimes Field doesn't come in the json-response, so then this code shows an error. As I cannot put useEffect inside some conditional statement (as per React Guidelines, all useEffects should always run in same order), is there any way I may add some code in dependency such as [field.length? field[1].text: null]. I am not sure.

Can someone help?


Solution

  • you can use optional chaining or && for this.

    useEffect(() => {
     if (field?[1]?.isActive === true) {
      handleMore();
     }
    }, [field?.[1]?.text]);
    

    Or

    useEffect(() => {
       if (field?[1]?.isActive === true) {
          handleMore();
       }
     }, [field && field[1] && field[0].text]);