2019-09-17 14:30:26 +09:00
|
|
|
import {useState, useEffect} from 'react';
|
2019-07-30 23:27:28 +09:00
|
|
|
|
2019-09-01 01:28:24 +09:00
|
|
|
export function useDeferredState<T>(
|
|
|
|
duration = 1000,
|
2019-09-17 14:30:26 +09:00
|
|
|
initialValue: T,
|
2019-09-01 01:28:24 +09:00
|
|
|
): [T, React.Dispatch<React.SetStateAction<T>>] {
|
2019-09-17 14:30:26 +09:00
|
|
|
const [response, setResponse] = useState(initialValue);
|
|
|
|
const [innerValue, setInnerValue] = useState(initialValue);
|
2019-07-30 23:27:28 +09:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const fn = setTimeout(() => {
|
2019-09-17 14:30:26 +09:00
|
|
|
setResponse(innerValue);
|
|
|
|
}, duration);
|
2019-07-30 23:27:28 +09:00
|
|
|
|
2019-12-24 01:57:07 +09:00
|
|
|
return (): void => {
|
2019-09-17 14:30:26 +09:00
|
|
|
clearTimeout(fn);
|
|
|
|
};
|
|
|
|
}, [duration, innerValue]);
|
2019-07-30 23:27:28 +09:00
|
|
|
|
2019-09-17 14:30:26 +09:00
|
|
|
return [response, setInnerValue];
|
2019-07-30 23:27:28 +09:00
|
|
|
}
|