'React Using dispatch in useEffect hook results in an infinite loop

i want to dispatch in UseEffect hook but i have problem infinite loop

const { ErrorLabel, ERROR_COUNT_TABLE } = useErrorCount();
... some codes
  useEffect(() => {
    if (!ErrorLabel) return;
    dispatch(setPinnedError(ErrorLabel));
  }, [ErrorLabel]);

useErrorCount is custom hook And this is useErrorCount.tsx

const useErrorCount = () => {
  const getCountedErrorType = () => {
    ... somecodes
    return COPY_ERROR_COUNT_TABLE;
  };

  const setErrorLabelCount = () => {
    const errorCountTable = getCountedErrorType();
    if (!errorCountTable) return;
    const countedErrorLabel: any = _.cloneDeep(ERRORLABEL);
    for (let i = 0; i < countedErrorLabel.length; i++) {
      const type: ErrorType = countedErrorLabel[i].name;
      countedErrorLabel[i].count = errorCountTable[type];
    }

    return countedErrorLabel;
  };

  return {
    ErrorLabel: setErrorLabelCount(),
  };
};

I use dependency array in useEffect hook but not stop infinite loop

I've used the useCallback hook, and use Empty depenency array in UseEffect like this

  const updatePinnedError = useCallback(() => {
    dispatch(setPinnedError(ErrorLabel));
  }, [ErrorLabel]);

  useEffect(() => {
    if (!ErrorLabel) return;
    updatePinnedError();
  }, []);

The infinite loop stops, but it should be dispatched whenever ErrorLabel is updated, but there is no change. How can I solve this problem?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source