I am trying to do some session verification when my page is initially loaded. The AuthenticationRequiredComponent
is used as a wrapper for other components that require authentication. If users are not logged in, they should be redirected to the login page. This component has a useEffect
callback defined with an empty dependency array, because it subscribes to an auth state change (it is using Firebase Auth). If I go through the whole process of logging in to my website, and get to a page that uses this wrapper, the useEffect
is called correctly. However, if I am in a page that uses this wrapper and I hit refresh or if I navigate directly to the url of a page that uses this wrapper, the useEffect
is not being called, which results in the page not working correctly. The project is fairly large, so I cannot post the entire code. I will add pseudocode of some of the parent elements for structure:
export const AuthenticationRequiredComponent = ({ children }) => {
const { session, dispatch } = useContext (SessionContext);
const navigate = useNavigate ();
const [ loadingLogin, setLoadingLogin ] = useState (false);
/* This is the useEffect() that is not running */
useEffect (() => {
return isLoggedIn (setLoadingLogin, doWithUser, handleError);
}, []);
useEffect (() => {
if (!session.loggedIn) {
navigate ("/login");
}
}, [ session ]);
function doWithUser ({ user, token }) {
dispatch ({ type: "login", user, token: token });
}
function handleError (err) {
console.error (err);
dispatch ({ type: "logout" });
}
return children;
};
/* This is the parent component */
const MainComponent = () => {
return <AuthenticationRequiredComponent>
<Navbar />
<Outlet />
</AuthenticationRequiredComponent>
}
/* This creates a "route" object, which is then passed to an upper level array,
and eventually a router is created through `createBrowserRouter`*/
export const businessRoute = {
path: ":businessId",
element: <MainComponent />,
errorElement: <>Error</>,
children: [
homeRoute,
...
]
};
I read the documentation on useEffect
, and it says that effects with empty dependency arrays are only run after the initial render. Why then are they not triggered when I refresh the page? When does this initial render happen? Looking around I also noticed that there are other components whose useEffect
with empty dependency arrays are not being called on similar scenarios. I would appreciate any help on figuring out why this is happening.