Skip to content

Instantly share code, notes, and snippets.

@arnonate
Last active September 23, 2020 17:44
Show Gist options
  • Save arnonate/bd8f24731c182189a187e1052f950bf9 to your computer and use it in GitHub Desktop.
Save arnonate/bd8f24731c182189a187e1052f950bf9 to your computer and use it in GitHub Desktop.
// 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