@susisu/use-debounced
v0.5.1
Published
React Hooks for debouncing state updates and function calls
Downloads
286
Readme
@susisu/use-debounced
React Hooks for debouncing state updates and function calls
# npm
npm i @susisu/use-debounced
# yarn
yarn add @susisu/use-debounced
# pnpm
pnpm add @susisu/use-debounced
Usage
useDebouncedState
useDebouncedState
is like the standard useState
hook, but state updates are debounced.
import React from "react";
import { useDebouncedState } from "@susisu/use-debounced";
const MyComponent: React.FC = () => {
const [value, setValue, isWaiting] = useDebouncedState({
init: "",
wait: 1000,
});
return (
<div>
<p>
<input
type="text"
defaultValue=""
onChange={e => {
setValue(e.target.value);
}}
/>
</p>
<p>{isWaiting ? "..." : value}</p>
</div>
);
};
useDebouncedCall
useDebouncedCall
debounces synchronous function calls. When the given function is invoked after timeout, the result will be set to the state.
import React from "react";
import { useDebouncedCall } from "@susisu/use-debounced";
const MyComponent: React.FC = () => {
const [user, call, isWaiting] = useDebouncedCall({
func: ([name]) => findUser(name),
init: undefined,
wait: 1000,
});
return (
<div>
<p>
<input
type="text"
defaultValue=""
onChange={e => {
call(e.target.value);
}}
/>
</p>
<p>{isWaiting ? "..." : user?.email}</p>
</div>
);
};
useDebouncedAsyncCall
useDebouncedAsyncCall
debounces asynchronous function calls. When the given function is invoked after timeout and it is fulfilled, the result will be set to the state.
import React from "react";
import { useDebouncedAsyncCall } from "@susisu/use-debounced";
const MyComponent: React.FC = () => {
const [user, call, isWaiting] = useDebouncedAsyncCall({
func: ([name]) => fetchUser(name).catch(() => undefined),
init: undefined,
wait: 1000,
});
return (
<div>
<p>
<input
type="text"
defaultValue=""
onChange={e => {
call(e.target.value);
}}
/>
</p>
<p>{isWaiting ? "..." : user?.email}</p>
</div>
);
};
useDebouncedFunc
useDebouncedFunc
is a simple hook to create a debounced version of a function.
import React from "react";
import { useDebouncedFunc } from "@susisu/use-debounced";
const MyComponent: React.FC = () => {
const [call] = useDebouncedFunc({
func: ([value]) => setRemoteValue(value),
wait: 1000,
});
return (
<div>
<p>
<input
type="text"
defaultValue=""
onChange={e => {
call(e.target.value);
}}
/>
</p>
</div>
);
};