Thuta Learning
IntermediateDevOps & Toolsintermediate

Checking login state

Relax. We'll talk through this in plain words — no textbook voice.

Checking login state

An auth state listener lets your app know whether a user is logged in, has logged out, or is still logged in after a page refresh. Whether the navbar shows a Login button or a Dashboard depends on this state.

Code Example

javascript
import { getAuth, onAuthStateChanged } from 'firebase/auth';

const auth = getAuth();

const unsubscribe = onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log('User is logged in:', user.uid);
  } else {
    console.log('No user. Show login page.');
  }
});

// Single-page app တွင် component မလိုတော့သောအခါ unsubscribe() ခေါ်နိုင်သည်။

What to watch out for

onAuthStateChanged also fires once when the app first loads. Because of that, it's better UX to keep a loading state and only render the page once you actually know whether a user exists.

Common mistake

If you keep re-attaching this listener inside a React/Vue component without cleaning it up, you can end up with a memory leak or duplicate console logs. Make sure to unsubscribe when the component unmounts.