Skip to content

Commit

Permalink
fix: more closely mimic use deferred value (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredLunde authored Apr 13, 2022
1 parent 39eab31 commit c5c2b73
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 18 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
"clsx": "^1.1.1",
"is-relative": "^1.0.0",
"trie-memoize": "^1.2.0",
"use-debounce": "^7.0.1",
"use-subscription": "^1.6.0",
"use-sync-external-store": "^1.0.0"
},
Expand Down
11 changes: 0 additions & 11 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 34 additions & 5 deletions src/use-deferred-value.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import {
clearRequestTimeout,
requestTimeout,
} from "@essentials/request-timeout";
import * as React from "react";
import { useDebounce as useDebounceBase } from "use-debounce";
import { perf } from "./utils";

export const useDeferredValue: <T>(
value: T,
Expand All @@ -9,11 +13,36 @@ export const useDeferredValue: <T>(
) => T =
typeof React.useDeferredValue === "function"
? (React.useDeferredValue as any)
: useDebounce;
: useThrottle;

function useDebounce<T>(
function useThrottle<T>(
value: T,
options: { timeoutMs: number } = { timeoutMs: 100 }
options: { timeoutMs: number } = { timeoutMs: 200 }
) {
return useDebounceBase(value, options.timeoutMs)[0];
const [state, setState] = React.useState<T>(value);
const lastInvocation = React.useRef<number>(0);
const waitedFor = React.useRef<number>(0);

React.useEffect(() => {
let didUnmount = false;
const now = perf.now();
waitedFor.current +=
now - (lastInvocation.current === 0 ? now : lastInvocation.current);
lastInvocation.current = now;

const timeout = requestTimeout(() => {
if (!didUnmount) {
setState(value);
waitedFor.current = 0;
lastInvocation.current = 0;
}
}, Math.max(options.timeoutMs - waitedFor.current, 0));

return () => {
didUnmount = true;
clearRequestTimeout(timeout);
};
}, [value, options.timeoutMs]);

return state;
}
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export function throttle<CallbackArguments extends any[]>(
};
}

const perf = typeof performance !== "undefined" ? performance : Date;
export const perf = typeof performance !== "undefined" ? performance : Date;

export function shallowEqual<
A extends Record<string | number | symbol, unknown> | null,
Expand Down

0 comments on commit c5c2b73

Please sign in to comment.