Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
React Hook recipe from
import Dashboard from "./Dashboard.js";
import Loading from "./Loading.js";
import { useRequireAuth } from "./use-require-auth.js";
function DashboardPage(props) {
const auth = useRequireAuth();
// If auth is null (still fetching data)
// or false (logged out, above hook will redirect)
// then show loading indicator.
if (!auth) {
return <Loading />;
return (
<Dashboard auth={auth} />
// Hook (use-require-auth.js)
import { useEffect } from "react";
import { useAuth } from "./use-auth.js";
import { useRouter } from "./use-router.js";
function useRequireAuth(redirectUrl = '/signup'){
const auth = useAuth();
const router = useRouter();
// If auth.user is false that means we're not
// logged in and should redirect.
useEffect(() => {
if (auth.user === false){
}, [auth, router]);
return auth;

This comment has been minimized.

Copy link

@topaztee topaztee commented Dec 17, 2019

(in use-auth.tx)
Isnt auth.user initially set at const [user, setUser] = useState(null);
so why it the check if (auth.user === false){ instaed of if(auth.user === null)?


This comment has been minimized.

Copy link
Owner Author

@gragland gragland commented Dec 17, 2019

@topaztee that’s because false means the user is logged out, whereas null means we’re still loading their authentication status. We only want to redirect once we know they are logged out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment