简体   繁体   中英

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 (ie 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

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM