typescriptbeginner

useFormDirty Hook

Tracks whether a form has unsaved changes and warns before page unload.

typescript
import { useState, useEffect, useCallback } from 'react';

export function useFormDirty() {
  const [isDirty, setIsDirty] = useState(false);

  const markDirty = useCallback(() => setIsDirty(true), []);
  const markClean = useCallback(() => setIsDirty(false), []);

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

    const handler = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      e.returnValue = '';
    };

    window.addEventListener('beforeunload', handler);
    return () => window.removeEventListener('beforeunload', handler);
  }, [isDirty]);

  return { isDirty, markDirty, markClean };
}

// Usage:
// const { isDirty, markDirty, markClean } = useFormDirty();
// <input onChange={() => { handleChange(); markDirty(); }} />
// On save: markClean();

Use Cases

  • Form unsaved-changes warning
  • Editor dirty state

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.