Conditional Gating Component for React Rendering

Sherry Hsu
1 min readMay 16, 2021

What does the pattern look like?

// Sign In Gateexport const SignInGate = ({ children }) => {  const user= useUser();  if (!user) return null;  return <div>{children}</div>;};
//------------------------------------------------
// use the Sign In Gateexport default function MembersOnly() { return ( <SignInGate> <MembersProduct /> </SignInGate> );}

Under what situation can this be used?

The Sign In Gate can be used in other area where we only want to show certain elements after the user has signed in. For instance, display members only content.

It can also be used in checking server/ client side rendering in SSR and avoid the UI flick when client renders over the existing server side rendered DOM.

Taking Josh Comeau’s example:

function ClientOnly({ children, ...delegated }) {  const [hasMounted, setHasMounted] = React.useState(false);  React.useEffect(() => {    setHasMounted(true);  }, []);  if (!hasMounted) {    return null;  }  return (    <div {...delegated}>      {children}    </div>  );}//-------------
// Render Navigation only in the client side!
<ClientOnly> <Navigation /></ClientOnly>

--

--

Sherry Hsu

A software engineer passionate about learning and growth