Skip to content

vkmalik/undo-redo-architecture

Repository files navigation

Undo/Redo Architecture (React + TypeScript)

A reusable, generic undo/redo system for React applications. Demonstrates state management best practices, type-safe hooks, and a scalable architecture for undoable actions.


What This Repo Shows

  • Generic, type-safe useUndoRedo hook
  • Maintains a history of past and future states
  • Undo and redo operations with a clean API
  • Decouples state management from UI logic
  • Works with any type of state: objects, arrays, primitives
  • Minimal, functional demo component

This pattern is suitable for real-world applications that require undoable state changes, such as editors, forms, or dashboards.


How It Works

  1. Import the hook and provide an initial state:
const { state, setState, undo, redo, canUndo, canRedo } = useUndoRedo({
  counter: 0,
});
  1. Update state as usual:
setState({ counter: state.counter + 1 });
  1. Undo or redo changes:
undo(); // revert to previous state
redo(); // redo last undone change
  • canUndo and canRedo indicate whether undo/redo is currently possible.
  • History and future stacks are managed automatically.

Bad Pattern

  • Directly mutating state without a history mechanism
  • Implementing undo/redo logic in multiple components individually
  • Leads to inconsistent behavior and hard-to-maintain code

Good Pattern (This Repo)

  • Centralized undo/redo logic via a generic hook
  • Type-safe and generic
  • Works with any React state
  • Clean separation between logic and UI
  • Scalable for multiple state types

Project Structure

src/
  hooks/
    useUndoRedo.ts       ← core hook logic
  components/
    UndoRedoDemo.tsx     ← demo UI to test hook
    UndoRedoDemo.css     ← styling
  App.tsx                ← integrates demo component

Demo

  • Increment and decrement a counter
  • Undo and redo state changes using buttons
  • Buttons are disabled when undo/redo is not possible

Installation

npm install
npm run dev

Open http://localhost:5173


License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published