useTransientState: implement hook
This utility hook provides access to a piece of state and a setter function, which can be used to supply a temporary value and a duration for which it is valid, before reverting to preceeding value. Following the pattern: const [value, setTransientValue] = useTransientValue<number>(42, 5000); setTransientValue(69); // value === 69 for 5000ms, before returning to 42 We can easily fire and forget a temporary state transition.
This commit is contained in:
16
src/hooks/useTransientState.ts
Normal file
16
src/hooks/useTransientState.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useTimeoutFn } from "react-use";
|
||||
|
||||
export default <T>(baseState: T, duration: number): [T, (setter: T) => void] => {
|
||||
const [value, setValue] = useState<T>(baseState);
|
||||
const [, , restart] = useTimeoutFn(() => setValue(baseState), duration);
|
||||
|
||||
useEffect(() => setValue(baseState), [baseState]);
|
||||
|
||||
const setTransientValue = (transientValue: T): void => {
|
||||
setValue(transientValue);
|
||||
restart();
|
||||
};
|
||||
|
||||
return [value, setTransientValue];
|
||||
};
|
||||
Reference in New Issue
Block a user