Recursive UseEffect in React

In React, useEffect let’s you perform side effects in function components. They are meant to run once when the component is mounted, however you can recursively call it by combining adding a useState data dependency to it. By toggling the value of the data dependency inside the effect, it recursively call the effect. This is useful, for example, in implementing retry logic to an API call say for automatically retrying when an access token expires.

const [retryToggle, setRetryToggle] = useState(false);

React.useEffect(() => {
  if (someConditionToPreventInfiniteLoop) {
    return
  }

  fetch("http://example.com")
    .then((r) => handleSuccessHere(r))
    .catch((err) => setRetryToggle( i=> !i))

  // This dependency allows us to re-run the effect whenever this
  // value changes.
}, [retryToggle]);