useDelayedValue
Delay update a value.
API
function useDelayedValue<T>(
value: T,
options:
| number
| {
delay: number;
include?: (value: any) => boolean;
compare?: (x: any, y: any) => boolean;
}
): T;
Params:
value
: The value will be delayed.options
: Accepts a positive number as the delay time or an object as the options.options.delay
: Delay time, in milliseconds. It must be a positive number.options.include
: A function that filters value to be delayed. Any value is delayed by default.options.compare
: It is used to compare whether two values are equal to determine whether to update the value. Default isObject.is
.
Example
The following example will show "Loading..."
after 500ms when you click the Toggle
button.
import React from "react";
import { useDelayedValue, useToggle } from "@lilib/hooks";
function Example() {
const [loading, { toggle }] = useToggle(false);
const delayedLoading = useDelayedValue(loading, {
delay: 500,
include: (value) => value === true,
});
return (
<div>
<button onClick={() => toggle()}>Toggle</button>
{delayedLoading && "Loading..."}
</div>
);
}
export default Example;