Skip to content

Commit

Permalink
debounced fetching the imageURL
Browse files Browse the repository at this point in the history
  • Loading branch information
coffee-cup committed May 14, 2021
1 parent 670db1c commit 3955158
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
18 changes: 18 additions & 0 deletions src/hooks/useDebouncedValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect, useState } from "react";

/**
* Returns new value equal to `value` after a debounce delay
*/
export const useDebouncedValue = <T>(value: T, delay: number): T => {
const [debouncedValue, setDebouncedValue] = useState(value);

useEffect(() => {
const timeout = setTimeout(() => {
setDebouncedValue(value);
}, delay);

return () => clearTimeout(timeout);
}, [value, delay]);

return debouncedValue;
};
8 changes: 5 additions & 3 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Select } from "../components/Select";
import { OG_HEIGHT, OG_WIDTH } from "../constants";
import { useConfig } from "../hooks/useConfig";
import { useCopy } from "../hooks/useCopy";
import { useDebouncedValue } from "../hooks/useDebouncedValue";
import { useIsMounted } from "../hooks/useIsMounted";
import { useLayoutConfig } from "../hooks/useLayoutConfig";
import { layouts } from "../layouts";
Expand Down Expand Up @@ -151,7 +152,7 @@ export const Viewer: React.FC = () => {
const [config] = useConfig();
const [layoutConfig] = useLayoutConfig();
const [isCopied, copy] = useCopy();
const [isLoaded, setIsLoaded] = useState(false);
const [isLoaded, setIsLoaded] = useState(true);

const query = useMemo(() => {
const searchParams = new URLSearchParams();
Expand All @@ -167,7 +168,8 @@ export const Viewer: React.FC = () => {
const imageURL = useMemo(() => `/api/image?${query}`, [query]);
const htmlURL = useMemo(() => `/api/html?${query}`, [query]);

useEffect(() => setIsLoaded(false), [imageURL]);
const debouncedImageURL = useDebouncedValue(imageURL, 200);
useEffect(() => setIsLoaded(false), [debouncedImageURL]);

return (
<div tw="space-y-4 w-full col-span-2">
Expand All @@ -185,7 +187,7 @@ export const Viewer: React.FC = () => {
filter: "blur(5px)",
},
]}
src={imageURL}
src={debouncedImageURL}
alt={`OG Image for the ${config.layoutName} layout`}
onLoad={() => setIsLoaded(true)}
/>
Expand Down

0 comments on commit 3955158

Please sign in to comment.