Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!