Persisted OTP

A resend button that waits thirty seconds, even across a reload.

Mounted

Two providers and a button. Reload while it counts: the wait is still there.

tsx
// react-graft-otp-resend-gate.tsx
export const ReactGraftOtpResendGate = () => (
  <ReactGraftOtpRequestGraft.Provider>
    <ReactGraftOtpCounterGraft.Provider>
      <ReactGraftOtpResendButton />
    </ReactGraftOtpCounterGraft.Provider>
  </ReactGraftOtpRequestGraft.Provider>
);

// react-graft-otp-resend-button.tsx
export const ReactGraftOtpResendButton = () => {
  const { counter, isCounting } = ReactGraftOtpCounterGraft.use();
  const { isSending, send } = ReactGraftOtpRequestGraft.use();

  return (
    <>
      <Button disabled={isCounting || isSending} onClick={send}>
        <Button.Label>{isCounting ? `resend in ${counter}s` : "send code"}</Button.Label>
      </Button>

      <Guard guardIf={!isSending} shouldHide>
        <Spinner />
      </Guard>
    </>
  );
};

Two grafts

One for the request, one for the wait. The wait depends on the request, so it sits below it.

tsx
// react-graft-otp-request.graft.ts — the moment the request is in flight
export const ReactGraftOtpRequestGraft = createGraft({ name: "ReactGraftOtpRequestGraft", graft: useGraft });

function useGraft() {
  return useSending({ delay: SEND_DELAY });
}

// react-graft-otp-counter.graft.ts — the wait that follows it
export const ReactGraftOtpCounterGraft = createGraft({
  name: "ReactGraftOtpCounterGraft",
  graft: useGraft,
  inject: [useInjectRestore, useInjectPersist, useInjectStart],
});

function useGraft() {
  return useCountdown({ duration: DURATION });
}

Persistence

Two injected effects: one saves when the wait ends, the other restores it on load.

tsx
// on arrival, pick the wait back up where it was
function useInjectRestore({ start }: { start: (seconds?: number) => void }) {
  useEffect(() => {
    const deadline = Number(window.localStorage.getItem(DEADLINE_KEY));
    if (!deadline) return;

    start(Math.ceil((deadline - Date.now()) / 1000));
  }, [start]);
}

// while it runs, write down where it ends
function useInjectPersist({ counter, isCounting }: { counter: number; isCounting: boolean }) {
  useEffect(() => {
    if (!isCounting) return window.localStorage.removeItem(DEADLINE_KEY);

    window.localStorage.setItem(DEADLINE_KEY, String(Date.now() + counter * 1000));
  }, [counter, isCounting]);
}

Starting the wait

The countdown starts when the request succeeds. The wait reads the request graft with use().

tsx
// the countdown begins when the request ends, not when it leaves
function useInjectStart({ start }: { start: (seconds?: number) => void }) {
  const { isSending } = ReactGraftOtpRequestGraft.use();
  const wasSending = useRef(isSending);

  useEffect(() => {
    if (wasSending.current && !isSending) start();

    wasSending.current = isSending;
  }, [isSending, start]);
}

The hooks

Each piece is a plain hook; the graft is what shares its state with the rest of the feature.

tsx
// react-graft-otp-request.graft.ts
function useSending({ delay }: { delay: number }) {
  const [isSending, setIsSending] = useState(false);

  const send = useCallback(() => setIsSending(true), []);

  useEffect(() => {
    if (!isSending) return;

    const timer = setTimeout(() => setIsSending(false), delay);

    return () => clearTimeout(timer);
  }, [delay, isSending]);

  return { isSending, send };
}

// react-graft-otp-counter.graft.ts — counts against a deadline, not against ticks
function useCountdown({ duration }: { duration: number }) {
  const [counter, setCounter] = useState(0);
  const [isCounting, setIsCounting] = useState(false);
  const deadlineRef = useRef<number | null>(null);

  const start = useCallback(
    (seconds = duration) => {
      const next = Math.max(0, seconds);
      if (!next) return;

      deadlineRef.current = Date.now() + next * 1000;
      setCounter(next);
      setIsCounting(true);
    },
    [duration],
  );

  useEffect(() => {
    if (!isCounting) return;

    const interval = setInterval(() => {
      const deadline = deadlineRef.current;
      if (deadline === null) return;

      const remaining = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
      setCounter(remaining);

      if (remaining > 0) return;

      deadlineRef.current = null;
      setIsCounting(false);
    }, 1000);

    return () => clearInterval(interval);
  }, [isCounting]);

  return { counter, isCounting, start };
}