skip to Main Content

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.

2

Answers


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

    useLayoutEffect(() => ...

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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search