Last updated

How to handle refresh loops in strict mode?

When wrapping your app with <React.StrictMode>, React intentionally invokes certain lifecycle methods and effects twice during development. This behavior is designed to help surface potential issues, but it can also impact SDKs like Frontegg’s in a few notable ways:

  • Double initialization - hooks such as useEffect may run twice, which can lead the Frontegg SDK to initialize more than once. This may result in duplicate authentication requests and redundant state updates, unintended side effects in initialization logic

  • Event Listener Duplication -if the SDK sets up event listeners within effects, these may be registered multiple times, leading to inconsistent behavior or unexpected interactions.

Impact on Hosted Login Behavior

Frontegg's hosted login implementation uses a /silent request to check if a valid refresh token cookie exists in the browser. If found, the SDK will attempt to automatically log the user in using useEffect.

Under <React.StrictMode>, this effect may run twice, causing:

  • Multiple silent login attempts

  • Extra redirects

  • A potentially degraded user experience due to flickering or delayed transitions

How to solve it

When working in developement mode, in order to prevent double redirects or redundant login attempts, you can add a guard using useRef to ensure the redirect is triggered only once:

import { useRef, useEffect } from 'react';
import { useLoginWithRedirect, useIsAuthenticated } from '@frontegg/react';

const loginWithRedirect = useLoginWithRedirectV2();
const initialRedirectAttempted = useRef(false);
const isAuthenticated = useIsAuthenticated();

useEffect(() => {
  if (!isAuthenticated && !initialRedirectAttempted.current) {
    initialRedirectAttempted.current = true;
    loginWithRedirect();
  }
}, [isAuthenticated, loginWithRedirect]);