Last active
April 6, 2020 17:12
-
-
Save icyJoseph/61eebf947bc3185c71f1b2ccde6f6639 to your computer and use it in GitHub Desktop.
A pattern to create a delayed suspense fallback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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