Skip to content

Instantly share code, notes, and snippets.

@heypiotr
Created September 6, 2022 13:54
Show Gist options
  • Save heypiotr/602ca88b9991ac9df2211d74598638ef to your computer and use it in GitHub Desktop.
Save heypiotr/602ca88b9991ac9df2211d74598638ef to your computer and use it in GitHub Desktop.
function OptimizationFriendly({ loading, loaded }) {
const [isLoading, setLoading] = React.useState(true)
React.useEffect(() => setLoading(false), [])
return isLoading ? loading : loaded
}
function LogInButton() { ... }
function GoToDashboardButton() { ... }
function MyComponent() {
// This isn't optimization-friendly because of "document"
const isLoggedIn = document.cookie.includes("session")
return isLoggedIn ? <GoToDashboardButton /> : <LogInButton />
}
export const MyOptimizationFriendlyComponent =
<OptimizationFriendly
// Always show the LogIn button while the page is loading,
// and thus showing the pre-rendered content.
loading={<LogInButton />}
// After the page loads, we'll check the actual logged-in
// status and either switch to the GoToDashboard button, or
// keep the LogIn button.
loaded={<MyComponent />}
/>
export const MyOptimizationFriendlyComponent =
<OptimizationFriendly
loading={null}
loaded={<MyComponent />}
/>
function withLoggedIn(Component) {
return (props) => {
// This isn't optimization-friendly because of "document"
const isLoggedIn = document.cookie.includes("session")
return <Component isLoggedIn={isLoggedIn} {...props} />
}
}
function withOptimizationFriendlyLoggedIn(Component) {
return (props) => {
const ComponentWithLoggedIn = withLoggedIn(Component)
return <OptimizationFriendly
loading={<Component isLoggedIn={false} {...props} />}
loaded={<ComponentWithLoggedIn {...props} />}
/>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment