React Firebase Hooks provides a convenience listener for Firebase Auth's auth state. The hook wraps around the firebase.auth().onAuthStateChange()
method to ensure that it is always up to date.
All hooks can be imported from react-firebase-hooks/auth
, e.g.
import { useAuthState } from 'react-firebase-hooks/auth';
List of Auth hooks:
const [user, loading, error] = useAuthState(auth);
Retrieve and monitor the authentication state from Firebase.
The useAuthState
hook takes the following parameters:
auth
:firebase.auth.Auth
instance for the app you would like to monitor
Returns:
user
: Thefirebase.User
if logged in, orundefined
if notloading
: Aboolean
to indicate whether the the authentication state is still being loadederror
: Anyfirebase.auth.Error
returned by Firebase when trying to load the user, orundefined
if there is no error
import { useAuthState } from 'react-firebase-hooks/auth';
const login = () => {
firebase.auth().signInWithEmailAndPassword('test@test.com', 'password');
};
const logout = () => {
firebase.auth().signOut();
};
const CurrentUser = () => {
const [user, loading, error] = useAuthState(firebase.auth());
if (loading) {
return (
<div>
<p>Initialising User...</p>
</div>
);
}
if (error) {
return (
<div>
<p>Error: {error}</p>
</div>
);
}
if (user) {
return (
<div>
<p>Current User: {user.email}</p>
<button onClick={logout}>Log out</button>
</div>
);
}
return <button onClick={login}>Log in</button>;
};