Skip to content

Instantly share code, notes, and snippets.

@icyJoseph
Last active April 6, 2020 17:12
Show Gist options
  • Save icyJoseph/61eebf947bc3185c71f1b2ccde6f6639 to your computer and use it in GitHub Desktop.
Save icyJoseph/61eebf947bc3185c71f1b2ccde6f6639 to your computer and use it in GitHub Desktop.
A pattern to create a delayed suspense fallback
import React, {
useEffect,
useState,
createContext,
useContext,
Suspense,
useMemo
} from "react";
const SlowSuspenseCtx = createContext({});
export const SlowSuspense = ({ children, fallback = null }) => {
const [show, setShow] = useState(false);
// you could take these timeout values as props to the Spinner
const remove = () => setTimeout(() => setShow(false), 500);
const activate = () => setTimeout(() => setShow(true), 250);
const value = useMemo(() => ({ activate, remove }), []);
return (
<SlowSuspenseCtx.Provider value={value}>
{show && fallback}
<Suspense fallback={<InvokeFallback />}>
<>{children}</>
</Suspense>
</SlowSuspenseCtx.Provider>
);
};
export const InvokeFallback = () => {
const { activate, remove } = useContext(SlowSuspenseCtx);
useEffect(() => {
let timer = activate();
return () => {
clearTimeout(timer);
remove();
};
}, [activate, remove]);
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment