How do I use the Firebase onAuthStateChange with the new React Hooks?
You can write a Custom Hook
which registers an effect and returns the auth state
const useFirebaseAuthentication = (firebase) => {
const [authUser, setAuthUser] = useState(null);
useEffect(() =>{
const unlisten = firebase.auth.onAuthStateChanged(
authUser => {
authUser
? setAuthUser(authUser)
: setAuthUser(null);
},
);
return () => {
unlisten();
}
}, []);
return authUser
}
export default useFirebaseAuthentication;
and in any Component
you can use it like
const MyComponent = (props) => {
const firebase = useContext(FirebaseContext);
const authUser = useFirebaseAuthentication(firebase);
return (...)
}
Index.jsx
will have this code in it
ReactDOM.render(
<FirebaseProvider>
<App />
</FirebaseProvider>,
document.getElementById('root'));
This Firebase Provider is defined like this,
import Firebase from './firebase';
const FirebaseContext = createContext();
export const FirebaseProvider = (props) => (
<FirebaseContext.Provider value={new Firebase()}>
{props.children}
</FirebaseContext.Provider>
);