Last active
September 23, 2020 17:44
-
-
Save arnonate/bd8f24731c182189a187e1052f950bf9 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
// useDebounce.ts | |
import React from "react"; | |
export default function useDebounce(value: string, delay: number = 500) { | |
const [debouncedValue, setDebouncedValue] = React.useState(value); | |
React.useEffect(() => { | |
const handler: NodeJS.Timeout = setTimeout(() => { | |
setDebouncedValue(value); | |
}, delay); | |
// Cancel the timeout if value changes (also on delay change or unmount) | |
return () => { | |
clearTimeout(handler); | |
}; | |
}, [value, delay]); | |
return debouncedValue; | |
} | |
// ConsumingComponent.tsx | |
import useDebounce from "../../hooks/useDebounce"; | |
import useReactQuery from "../../hooks/useReactQuery"; | |
export type ContainerProps = { | |
searchQuery: string; | |
isFetchingCallback: (key: boolean) => void; | |
}; | |
export const Container = ({ | |
searchQuery, | |
isFetchingCallback, | |
}: Readonly<ContainerProps>): JSX.Element => { | |
const debouncedSearchQuery = useDebounce(searchQuery, 600); | |
const { status, data, error, isFetching } = useReactQuery( | |
debouncedSearchQuery, | |
page | |
); | |
React.useEffect(() => isFetchingCallback(isFetching), [ | |
isFetching, | |
isFetchingCallback, | |
]); | |
return ( | |
<> | |
{data} | |
{/* <ReactQueryDevtools /> */} | |
</> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment