mirror of
https://github.com/Sendouc/sendou.ink.git
synced 2026-04-10 12:14:37 -05:00
34 lines
822 B
TypeScript
34 lines
822 B
TypeScript
import * as React from "react";
|
|
|
|
// TODO: fix causes memory leak
|
|
/** @link https://stackoverflow.com/a/64983274 */
|
|
export const useTimeoutState = <T>(
|
|
defaultState: T,
|
|
): [
|
|
T,
|
|
(action: React.SetStateAction<T>, opts?: { timeout: number }) => void,
|
|
] => {
|
|
const [state, _setState] = React.useState<T>(defaultState);
|
|
const [currentTimeoutId, setCurrentTimeoutId] = React.useState<
|
|
NodeJS.Timeout | undefined
|
|
>();
|
|
|
|
const setState = React.useCallback(
|
|
(action: React.SetStateAction<T>, opts?: { timeout: number }) => {
|
|
if (currentTimeoutId != null) {
|
|
clearTimeout(currentTimeoutId);
|
|
}
|
|
|
|
_setState(action);
|
|
|
|
const id = setTimeout(
|
|
() => _setState(defaultState),
|
|
opts?.timeout ?? 4000,
|
|
);
|
|
setCurrentTimeoutId(id);
|
|
},
|
|
[currentTimeoutId, defaultState],
|
|
);
|
|
return [state, setState];
|
|
};
|