typescript 51 lines · 7 steps

A debounced auto-save hook in React

A custom hook debounces form changes, cancels stale saves, and flushes on unload so no draft is lost.

Explained by highlit
1import { useEffect, useRef, useCallback } from "react";
2 
3type DraftPayload = Record<string, unknown>;
4 
5async function persistDraft(id: string, payload: DraftPayload, signal: AbortSignal) {
6 const res = await fetch(`/api/drafts/${id}`, {
7 method: "PUT",
8 headers: { "Content-Type": "application/json" },
9 body: JSON.stringify(payload),
10 signal,
11 });
12 if (!res.ok) throw new Error(`Draft save failed: ${res.status}`);
13}
14 
15export function useAutoSaveDraft(draftId: string, values: DraftPayload, delay = 800) {
16 const timer = useRef<ReturnType<typeof setTimeout>>();
17 const controller = useRef<AbortController>();
18 const lastSaved = useRef<string>("");
19 
20 const flush = useCallback(async () => {
21 const snapshot = JSON.stringify(values);
22 if (snapshot === lastSaved.current) return;
23 
24 controller.current?.abort();
25 controller.current = new AbortController();
26 
27 try {
28 await persistDraft(draftId, values, controller.current.signal);
29 lastSaved.current = snapshot;
30 } catch (err) {
31 if ((err as Error).name !== "AbortError") {
32 console.error("Auto-save error", err);
33 }
34 }
35 }, [draftId, values]);
36 
37 useEffect(() => {
38 clearTimeout(timer.current);
39 timer.current = setTimeout(flush, delay);
40 return () => clearTimeout(timer.current);
41 }, [flush, delay]);
42 
43 useEffect(() => {
44 const onLeave = () => {
45 clearTimeout(timer.current);
46 navigator.sendBeacon(`/api/drafts/${draftId}`, JSON.stringify(values));
47 };
48 window.addEventListener("beforeunload", onLeave);
49 return () => window.removeEventListener("beforeunload", onLeave);
50 }, [draftId, values]);
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Debouncing plus a saved-snapshot comparison avoids redundant network writes on every keystroke.
  2. 2AbortController lets a new save cancel the in-flight one so responses never arrive out of order.
  3. 3sendBeacon on beforeunload rescues data the debounce timer never got to flush.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A debounced auto-save hook in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code