0

In my react app in my <Login \> component I check if user has a valid JWT with useEffect hook and then redirect them to "/" .

But every time I try to access the "/login" route I see a flicker for a second (showing my login form) and then i get redirected to the homepage.

Is there anyway to get away from this flicker?

I tried conditional routing in my routes in App.js file to check user JWT and if it's valid, redirect to homepage and if not render <Login /> component.

<Route path="/login" element={ isValid ? <Navigate to={"/"} replace /> : <Login /> }

But the problem still remains and there is a flicker.

Is there a way to avoid this flicker? or it's just normal.

[FIXED]

I was using promises inside my useEffect to validate the token and then using the useState hook to set the authentication state of users.

Then I noticed that if I put a loading component until the validation gets done, the useEffect hook (validation) will never run and will never check the JWT and run the setAuthState(true) because it's stuck on a loading component.

if (authState === undefined) return <Loading />

So, I replaced the code in promises with an async function to await the value and set the authentication state and get this done.

AliBot
  • 11
  • 4
  • I think it would be better to show a loader component until you have the value of JWT token. Once you have the value, based on that show the login form or navigate him to the next page. – Gavara.Suneel Jun 12 '23 at 11:09
  • maybe this can help you: https://stackoverflow.com/questions/45089386/what-is-the-best-way-to-redirect-a-page-using-react-router – Sam Levine Jun 12 '23 at 11:12
  • @Gavara.Suneel Yeah I was planning to do this but because I was using promises inside my useEffect the value of JWT would never change actually because the code would stuck on a loading component, I fixed the problem by using an async function instead of promises to await the value before showing loading component. – AliBot Jun 13 '23 at 06:50

2 Answers2

0

Use the useLayoutEffect hook instead. This will fire just before the screen repaints.

useLayoutEffect(() => ...

https://react.dev/reference/react/useLayoutEffect

P Savva
  • 309
  • 1
  • 5
0

When on CSR, It cannot be done, the component needs to be rendered first, then it will decide whether to redirect the client or not, to do so, use a server side validation for your session and redirect the user from the server, not from user's client.