# Using @auth0/auth0-react and getAccessTokenSilently in useEffect leads to infinite loop

**URL:** <https://community.auth0.com/t/using-auth0-auth0-react-and-getaccesstokensilently-in-useeffect-leads-to-infinite-loop/104855>\
**Category:** Get Help\
**Tags:** login-experience, new-universal-login-experience\
**Created:** [April 17, 2023, 10:36am UTC](https://community.auth0.com/t/using-auth0-auth0-react-and-getaccesstokensilently-in-useeffect-leads-to-infinite-loop/104855 "2023-04-17T10:36:30Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![dgeo](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@dgeo](https://community.auth0.com/u/dgeo)\
**Post date:** [April 17, 2023, 10:36am UTC](https://community.auth0.com/t/using-auth0-auth0-react-and-getaccesstokensilently-in-useeffect-leads-to-infinite-loop/104855/1 "2023-04-17T10:36:30Z")

</div>

Hi team,

I am following the React Authentication By Example:Using React Router 6 [1]. I am using the following dependencies:

```auto
react-router-dom 6.3.0
react 18.2 
auth0-react 2.0.1

```

Everything works fine until I try to call getAccessTokenSilently() inside useEffect() which causes an infinite loop. I searched all related topics but couldn’t find a solution.

Minimal code snippets for repro (following closely the tutorial above):

Auth0ProviderWithNavigate implementation:

```auto
import { Auth0Provider } from '@auth0/auth0-react';
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

export const Auth0ProviderWithNavigate = ({ children }) => {
  const navigate = useNavigate();
  const onRedirectCallback = (appState) => {
    navigate(appState?.returnTo || window.location.pathname);
  };

  if (!(domain && clientId && redirectUri)) {
    return null;
  }

  return (
    <Auth0Provider
      domain={domain}
      clientId={clientId}
      authorizationParams={{
        audience: audience,
        redirect_uri: redirectUri
      }}
      onRedirectCallback={onRedirectCallback}
      useRefreshTokens={true}
    >
      {children}
    </Auth0Provider>
  );
};

```

AuthenticationGuard is included on all routes that require authentication:

```auto
import { withAuthenticationRequired } from '@auth0/auth0-react';

export const AuthenticationGuard = ({ component }) => {
  const Component = withAuthenticationRequired(component, {
    onRedirecting: () => (
      <div className="page-layout">
        Loading...
      </div>
    ),
  });

  return <Component />;
};

```

index.tsx implementation:

```auto
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
import { Auth0ProviderWithNavigate } from './Auth0Provider';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
  <React.Fragment>
    <BrowserRouter>
      <Auth0ProviderWithNavigate>
        <App />
      </Auth0ProviderWithNavigate>
    </BrowserRouter>
  </React.Fragment>
);

reportWebVitals();

```

App.tsx which I also see to be called infinitely after I check getAccessTokenSilently() in useEffect():

```auto
import * as React from 'react';
import { Routes, Route } from 'react-router-dom';
import Home from 'pages/Home';
import { AuthenticationGuard } from 'components/AuthenticationGuard';
import { AppProvider } from './context';

export default function App(): JSX.Element {
  const { isAuthenticated } = useAuth0();
  console.log('isAuthenticated: ', isAuthenticated); // <------------ this prints in infinite loop
  return (
    <React.Fragment>
      <AppProvider>
          <Routes>
            <Route path="/" element={<AuthenticationGuard component={Home} />} />
          </Routes>
        </div>
      </AppProvider>
    </React.Fragment>
  );
}

```

AppProvider implementation:

```auto
import React, { createContext, useReducer } from 'react';

const AppProvider = ({ children }: ProviderProps) => {
  const [state, dispatch] = useReducer(combinedReducers, initialState);
  return <AppContext.Provider value={{ state, dispatch }}>{children}</AppContext.Provider>;
};
export { AppProvider };

```

Home component implementation where the infinite loop happens:

```auto
import * as React from 'react';
import { useEffect } from 'react';

export default function Home(): JSX.Element {
  useEffect(() => {
    (async () => {
      const token = await getAccessTokenSilently({
        authorizationParams: {
          audience: audience
        },
      });
    console.log('token ', token); // <----------- this prints in infinite loop
    })();
  }, []);

  return (
    <div>Hello from app!</div>
  );
}

```

When I call getAccessTokenSilently to access my own api, I don’t experience any issues. It only happens when trying to use getAccessTokenSilently in useEffect. Any pointers on how to resolve this or ideas about why is this happening will be much appreciated. Many thanks!!

[1] [React Authentication By Example: Using React Router 6](https://developer.auth0.com/resources/guides/spa/react/basic-authentication)

---

<div class="post-metadata">

**Author:** ![zachary.willard](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/zachary.willard/32/38837_2.png) [@zachary.willard](https://community.auth0.com/u/zachary.willard)\
**Post date:** [April 17, 2023, 2:00pm UTC](https://community.auth0.com/t/using-auth0-auth0-react-and-getaccesstokensilently-in-useeffect-leads-to-infinite-loop/104855/2 "2023-04-17T14:00:52Z")

</div>

Does adding `useRefreshTokensFallback={true}` to `<Auth0Provider />` help?

I ran into a similar issue and this might help you.

Related thread: [Auth0 spa 2.x returning missing\_refresh\_token - #18 by frederik.prijck](https://community.auth0.com/t/auth0-spa-2-x-returning-missing-refresh-token/98999/18)

---

<div class="post-metadata">

**Author:** ![dgeo](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@dgeo](https://community.auth0.com/u/dgeo)\
**Post date:** [April 17, 2023, 5:16pm UTC](https://community.auth0.com/t/using-auth0-auth0-react-and-getaccesstokensilently-in-useeffect-leads-to-infinite-loop/104855/3 "2023-04-17T17:16:13Z")

</div>

> [@zachary.willard](#):
>
> useRefreshTokensFallback={true}

The result is still the same after adding useRefreshTokensFallback to `<Auth0Provider />`

I see the linked post is for `auth0-spa-js`, however, I am only using `auth0-react`.

---

<div class="post-metadata">

**Author:** ![dgeo](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@dgeo](https://community.auth0.com/u/dgeo)\
**Post date:** [April 18, 2023, 8:20pm UTC](https://community.auth0.com/t/using-auth0-auth0-react-and-getaccesstokensilently-in-useeffect-leads-to-infinite-loop/104855/4 "2023-04-18T20:20:38Z")

</div>

I’ve root caused this issue to be due to the usage of `withAuthenticationRequired` inside `< AuthenticationGuard />` on the route for Home component. However, I don’t understand fully why the `withAuthenticationRequired` cause the infinite loop.

---

<div class="post-metadata">

**Author:** ![NikolaP](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@NikolaP](https://community.auth0.com/u/NikolaP)\
**Post date:** [May 11, 2023, 2:46pm UTC](https://community.auth0.com/t/using-auth0-auth0-react-and-getaccesstokensilently-in-useeffect-leads-to-infinite-loop/104855/5 "2023-05-11T14:46:29Z")

</div>

Hey @dgeo have you found any solution for this problem? I’m stuck with same.

---

<div class="post-metadata">

**Author:** ![zamashkin](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/zamashkin/32/52110_2.png) [@zamashkin](https://community.auth0.com/u/zamashkin)\
**Post date:** [October 31, 2023, 4:44pm UTC](https://community.auth0.com/t/using-auth0-auth0-react-and-getaccesstokensilently-in-useeffect-leads-to-infinite-loop/104855/6 "2023-10-31T16:44:26Z")

</div>

If someone is still stuck with this problem maybe I have a solution - I had infinite loop after i started using `withAuthenticationRequired` and `getAccessTokenSilently` in `useEffect` in child component that renders after authorization.

Adding `audience` into `authorizationParams` object for configuring Auth0Provider somehow fixed it.

My Auth0Provider params looking like this now -

```auto
<Auth0Provider
      domain={domain}
      clientId={clientId}
      authorizationParams={{
        redirect_uri: window.location.origin,
        audience: audience,
      }}
    >
        <App />
    </Auth0Provider>

```

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [July 30, 2024, 12:35pm UTC](https://community.auth0.com/t/using-auth0-auth0-react-and-getaccesstokensilently-in-useeffect-leads-to-infinite-loop/104855/7 "2024-07-30T12:35:10Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
