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

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { DataSource } from 'typeorm';

Per-tenant database connections in NestJS

multi-tenancy connection-pooling dependency-injection
Advanced 8 steps

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