Home > Mobile >  In React, does a return statement return immediately or does it wait for the UseEffect to finish?
In React, does a return statement return immediately or does it wait for the UseEffect to finish?

Time:08-16

I am following a Youtube tutorial in which I am building a full stack Instagram clone with Firebase v8. I am having trouble understanding the following Custom Hook in which we are checking if the user is already logged in:

import { useState, useEffect, useContext } from "react";
import FirebaseContext from "../context/firebase";

export default function useAuthListener() {
  const [user, setUser] = useState(
    JSON.parse(localStorage.getItem("authUser"))
  );
  const { firebase } = useContext(FirebaseContext);

  useEffect(() => {
    const listener = firebase.auth().onAuthStateChanged((authUser) => {
      if (authUser) {
        // we have a user...therefore we can store the user in localstorage
        localStorage.setItem("authUser", JSON.stringify(authUser));
        setUser(authUser);
      } else {
        // we don't have an authUser, therefore clear the localstorage
        localStorage.removeItem("authUser");
        setUser(null);
      }
    });

    return () => listener();
  }, [firebase]);

  return { user };
}

So we are checking if the user is logged in to conditionally render some components.

My question: Suppose I call this Hook in my Home.js component, AND there is already a user in the local storage, then does this hook immediately return that user or does it wait for the useEffect hook to run and get info from the firebase server? Also, is there a need to pass firebase in the dependency array [since firebase is a constant]?

CodePudding user response:

Either way, 'user' will always be returned first and only then the code in useEffect will run.

I quote the docs: ".. useEffect will run after the render is committed to the screen." In a shorter and simpler statement: useEffect runs only after the component finished rendering its JSX.

You don't need to add 'firebase' because you've already created a listener that will cause 'user' state to alter, thus re-rendering your DOM again(AND creating a new listener again).

  • Related