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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Debouncing plus a saved-snapshot comparison avoids redundant network writes on every keystroke.
- 2AbortController lets a new save cancel the in-flight one so responses never arrive out of order.
- 3sendBeacon on beforeunload rescues data the debounce timer never got to flush.
Related explainers
java
@Aspect @Component public class IdempotencyAspect {
How an idempotency aspect works in Spring
aop
idempotency
caching
Advanced
9 steps
typescript
type Curried<A extends any[], R> = A extends [infer First, ...infer Rest] ? (arg: First) => Rest extends [] ? R : Curried<Rest, R> : R;
Type-safe currying in TypeScript
currying
conditional-types
recursion
Advanced
8 steps
java
package com.example.orders.messaging; import com.example.orders.dto.OrderEvent; import com.example.orders.service.OrderProcessingService;
Manual RabbitMQ acks in a Spring listener
message-queue
error-handling
acknowledgement
Intermediate
6 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpHandler,
Refreshing tokens with an Angular HttpInterceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
typescript
type StorageSchema = Record<string, unknown>; interface StorageOptions { namespace?: string;
A type-safe wrapper around localStorage
generics
type-safety
serialization
Intermediate
9 steps
typescript
type Fetcher<T> = (key: string) => Promise<T>; export class RequestDeduplicator<T> { private inFlight = new Map<string, Promise<T>>();
Deduplicating in-flight requests in TypeScript
deduplication
promises
caching
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-debounced-auto-save-hook-in-react-explained-typescript-4501/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.