Created
May 8, 2023 10:55
-
-
Save drcmda/b261f485e0ad7e8de881b8a7b597f6be to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { Suspense, createContext, useTransition, useState, useContext, useMemo } from 'react' | |
import debounce from 'lodash/debounce' | |
const pendingContext = createContext() | |
export function Pending({ fallback, debounce, children }) { | |
return ( | |
<Suspense fallback={fallback}> | |
<PendingChildren debounce={debounce}>{children}</PendingChildren> | |
</Suspense> | |
) | |
} | |
function PendingChildren({ children, debounce = 100 }) { | |
const [pending, start] = useTransition() | |
const api = useMemo(() => [pending, start, debounce], [pending, start, debounce]) | |
return <pendingContext.Provider value={api}>{children}</pendingContext.Provider> | |
} | |
export function usePendingState(initialState, customDelay) { | |
const [, start, delay] = useContext(pendingContext) | |
const [value, setValue] = useState(initialState) | |
const [set] = useState(() => debounce(value => start(() => setValue(value)), customDelay ?? delay)) | |
return [value, set] | |
} | |
export function usePending() { | |
return useContext(pendingContext)[0] | |
} |
Author
drcmda
commented
May 8, 2023
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment