title: How can I avoid infinite loops in my React Router private routes?
body: <p>In my App.js, I have some authenticated pages I protect with <code>&lt;PrivateRoute&gt;</code>, like so:</p>
  <pre><code>&lt;PrivateRoute path=&quot;/dashboard&quot;&gt;
    &lt;Dashboard /&gt;
  &lt;/PrivateRoute&gt;
  </code></pre>
  <p>I implement <code>&lt;PrivateRoute&gt;</code> like so:</p>
  <pre><code>function PrivateRoute({ children, ...rest }) {
    return (
      &lt;Route {...rest} render={() =&gt; &lt;CheckRedirect children={children} /&gt;} /&gt;
    );
  }
  </code></pre>
  <p>The problem is, the <code>&lt;CheckRedirect&gt;</code> function calls out to an endpoint on my server which <strong>dynamically tells you where to redirect</strong>.</p>
  <p>Here's the function:</p>
  <pre><code>export const CheckRedirect = ({ children }) =&gt; {
    const [isChecking, setIsChecking] = React.useState(true);
    const [target, setTarget] = React.useState(null);
  
    const url = &quot;https://example.com/get-redirect&quot;
  
    useEffect(() =&gt;{
      async function getPage() {
        axios.get(url)
        .then(function (response) {
          setTarget(response.data.message)
        }).finally(() =&gt; setIsChecking(false))
      }
      
      getPage();  
    }, []);
  
    if (isChecking) {
      return &quot;... Checking&quot;;
    }
  
    return {target} ? (
      &lt;Redirect to={target} /&gt;
    ) : (
      &lt;Redirect to='/404' /&gt;
    );
  };
  </code></pre>
  <p>If you're not logged in, it will send back &quot;/login&quot; in the <code>message</code> field. If you're logged in, it will send &quot;/dashboard&quot;.</p>
  <p>If it sends back &quot;/dashboard&quot;, then React Router <em>produces an infinite loop!</em> It tries the same <code>&lt;PrivateRoute&gt;</code> again, which calls out to the endpoint again, which will once again return &quot;/dashboard&quot;, and so on...</p>
  <p>Is there a way I can tell my <code>&lt;PrivateRoute&gt;</code> to <em>not</em> do the <code>&lt;CheckRedirect&gt;</code> function if this is already the result of a redirect?</p>