In App Authentication
Persisting Sign-in State
When a user signs in, leaves the app, and then returns, you want to be able to persist their authenticated state. That way they don't have to sign in every single time they want to use the app.
To accomplish this, we need to do the following:
Upon successful sign in, store JSON web token in local storage.
When app first loads, check if that JSON web token is in local storage.
If it is, navigate the user to an authenticated screen.
If it doesn't, navigate the user to the sign-in or sign-up screen.
Here's the functions we need to accomplish our goals:
Now we can use hydrateSignIn
in the initial screen that appears when the app first loads. Maybe that first screen is the SignUpScreen
.
When the user then opens up the app, it will check if the user is already signed in and then navigate them to the appropriate screen.
Preventing initial screen flicker
In the example above, suppose the user is signed in already, and we redirect them to some HomeScreen
that is only available to display authenticated content.
The trouble with the above approach is that SignUpScreen
will appear for a split second before redirecting th user to the HomeScreen
. That's because useEffect
runs after mount. This is visually awkward.
To solve this, we can make the initial screen into a ResolveAuthScreen
that returns nothing.
Now when the app first loads, the user will see a blank screen for a split second and then be redirected to the appropriate screen.
Last updated