Function useCooldownState

  • This hook wraps the standard useState hook but provides a way to block state updates for a provided amount of time. Further state updates during this cooldown time are discarded.

    Type Parameters

    • T

    Parameters

    • initialState: T

      The initialState passed to the useState hook.

    • delay: number

      The amount of time in milliseconds to block consecutive state updates.

    Returns [T, ((newValue: T) => void), ((newValue: T) => void)]

    An array containing the read-only state (index 0), the setState function (index 1) which enforces the cooldown on updates, and another setState function (index 2) which forces a state update independent of the cooldown.

    const Page = () => {
    const [state, setState, forceUpdate] = useCooldownState(true, 1000);
    return (
    <>
    <h1>
    My favorite color is: {state ? "green" : "red"}
    </h1>
    <button onClick={() => setState(!state)}>Change Opinion</button>
    <button onClick={() => forceUpdate(!state)}>Change Opinion Immediately</button>
    </>
    );
    };