Skip to content

Instantly share code, notes, and snippets.

@danieljpgo
Last active August 13, 2021 17:54
Show Gist options
  • Save danieljpgo/991b549b547d7e266a92c6876d07bbe5 to your computer and use it in GitHub Desktop.
Save danieljpgo/991b549b547d7e266a92c6876d07bbe5 to your computer and use it in GitHub Desktop.
import * as React from 'react';
type FallbackProps = {
element: React.ReactNode;
delay?: number;
}
function Fallback(props: FallbackProps) {
const { delay = 300, element } = props;
const [ready, setReady] = React.useState(false);
React.useLayoutEffect(() => {
const timeout = setTimeout(() => setReady(true), delay);
return () => clearTimeout(timeout);
}, [delay]);
return (
<>
{ready && element}
</>
);
};
type SuspenseWithDelayProps = {
fallback: React.ReactNode;
children: React.ReactNode;
delay?: number;
}
export default function SuspenseWithDelay(props: SuspenseWithDelayProps) {
const { fallback, delay, children } = props;
return (
<React.Suspense fallback={<FallbackWithDelay delay={delay} element={fallback} />}>
{children}
</React.Suspense>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment