5
2 Comments

How to write a requireAuth Higher Order Component

A lot of React discussion these days focuses on hooks, but sometimes an HOC (or Higher Order Component) is the right tool for the job, particularly when you want to be able to avoiding rendering the passed in component in certain cases. Here's an example of how you might implement a requireAuth HOC.

function requireAuth(Component){
  return (props) => {
    // Let's assume we have a hook for getting auth state
    const auth = useAuth();

    useEffect(() => {
      // Redirect if not signed in
      if (auth.isAuthenticated === false) {
        // Use replace instead of push so you don't break back button
        router.replace("/signin");
      }
    }, [auth]);
    
    return auth.isAuthenticated === true
      // Render component passed into requireAuth
      ? <Component {...props} />
      // Show loading if not signed in (redirect is about to happen)
      // or while waiting on auth state (isAuthenticated is undefined)
      : <PageLoader />
  };
};

// Usage: Simply wrap any component when exporting
export default requireAuth(AccountPage);
  1. 2

    From a react noob's perspective, please keep these insights coming!

    1. 2

      Glad you like it! Will keep sharing.

Trending on Indie Hackers
Passed $7k 💵 in a month with my boring directory of job boards 39 comments Reaching $100k MRR Organically in 12 months 32 comments 87.7% of entrepreneurs struggle with at least one mental health issue 14 comments How to Secure #1 on Product Hunt: DO’s and DON'Ts / Experience from PitchBob – AI Pitch Deck Generator & Founders Co-Pilot 11 comments Competing with a substitute? 📌 Here are 4 ad examples you can use [from TOP to BOTTOM of funnel] 10 comments Are you wondering how to gain subscribers to a founder's X account from scratch? 9 comments