Previously, we implemented authentication for this Firebase in React application. Along the way, we added authorization with roles. You may have experienced a flicker every time you reload/refresh your browser, because the application doesnât know from the start if a user is authenticated or not since the authenticated user is null. It will happen until Firebase figures out there is an authenticated user and calls the function in the listener of the authentication higher-order component:
After the Firebase authentication listener is invoked for the first time, the authenticated user may be there, because Firebase has its internal state for auth persistence. Also, the routes are made visible in the Navigation component due to the authenticated user being there now. While itâs good that Firebase keeps the state of the authenticated user, the UI glitch in the beginning hurts the user experience. Letâs avoid this using the browserâs local storage for the authenticated user:
Every time Firebaseâs listener is invoked, the authenticated user is not only stored in the local state, ready to be passed to Reactâs Context API, but itâs also stored in the browserâs local storage. You can use the local storageâs API with setItem and removeItem to store and delete something identified by a key. You also need to format the authenticated user to JSON before you can put it into the local storage of the browser.
The flicker is still there, because weâre not really taking advantage of having the authenticated user earlier at our disposal. Letâs change this by retrieving it from the local storage in the higher-order componentâs constructor earlier:
If there is no auth user in the local storage, the local state will stay null and everything will remain as before. However, if the authenticated user is in the local storage because it was stored via our Firebase listenerâs function, we can use it in the componentâs constructor. Since the format of the authenticated user in the local storage is JSON, we need to transform it into a JavaScript object again. Ultimately, someone using our application can refresh the browser, but also close the browser/tab and open it after a while, and it will still see them as an authenticated user.
Try the application again and verify that the flicker is gone. Also all the conditional routes and pages that are protected with a conditional rendering (e.g. Navigation component) or authorization (e.g. HomePage component) should be there immediately. The authentication higher-order component can pass the authenticated user with its first render via Reactâs Context API to all other components.