Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
useEffect with function that update the state as dependency leads to infinite loop

Code Sandbox: https://codesandbox.io/s/new-breeze-d260k

The code:

  • This is a simple auth app
  • When you click Login, the accessToken is exchanged and stored in memory while the refreshToken is stored in localStorage.
  • While the accessToken is valid (here a timestamp), the Home page shows the protected content
  • At every page reload (i.e App initialization), the refreshToken is sent to the server and if it is valid, a new accessToken is exchanged.

The problem:

  • To refresh the token on App initialization, I have an onRefreshToken() function in a useEffect to be executed once (I wanted to pass an empty array as dependency but typescript/eslint complains and suggest that onRefreshToken() should be the dependency. I admit that I don't understand why this is recommended to have always a dependency when you want the effect to be executed once).
  • Once the token is renewed, I store the accessToken and the user profile in their respective context.
  • Infinite re-render loop begins. On my local server, this is due to setProfile() and not setAccessToken(). However I don't understand why.

Side note

The above issue is the main issue of this post but on a side note, the login/logout process don't sync between tabs so if you have any idea why, I would be happy to hear your advice on this point as well.

Happy new year

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

One way to fix this would be to check to see if you have an access token and only refresh it if you need to:

export default function App() {
  const { accessToken } = useAuthContext();
  const { onRefreshToken, onSyncLogin, onSyncLogout } = useAuth();

  useEffect(() => {
    const refresh = async () => {
      await onRefreshToken();
    };
    !accessToken && refresh();
  }, [onRefreshToken, accessToken]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda