useTransientState: set default delay (1000ms) and resolve retriggers
When setTransientState() triggers a new timeout, we clear any pending timeouts to prevent stale state from being applied if a superceding value was set in the interim. Maybe in future we should also allow users to cancel pending transitions directly, by returning useTimeoutFn's cancel() function along with the state and setter.
This commit is contained in:
@@ -1,11 +1,15 @@
|
|||||||
|
/* eslint-disable */
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { useTimeoutFn } from "react-use";
|
import { useTimeoutFn } from "react-use";
|
||||||
|
|
||||||
export default <T>(baseState: T, duration: number): [T, (setter: T) => void] => {
|
export default <T>(baseState: T, ms: number = 1000): [T, (transientValue: T) => void] => {
|
||||||
const [value, setValue] = useState<T>(baseState);
|
const [value, setValue] = useState<T>(baseState);
|
||||||
const [, , restart] = useTimeoutFn(() => setValue(baseState), duration);
|
const [, cancel, restart] = useTimeoutFn(() => setValue(baseState), ms);
|
||||||
|
|
||||||
useEffect(() => setValue(baseState), [baseState]);
|
useEffect(() => {
|
||||||
|
cancel();
|
||||||
|
setValue(baseState);
|
||||||
|
}, [baseState, ms]);
|
||||||
|
|
||||||
const setTransientValue = (transientValue: T): void => {
|
const setTransientValue = (transientValue: T): void => {
|
||||||
setValue(transientValue);
|
setValue(transientValue);
|
||||||
|
|||||||
Reference in New Issue
Block a user