Professional Todo Dashboard

A comprehensive task management application showcasing Mesa's fine-grained reactivity with advanced features like priority management, categorization, search, and analytics.

This example demonstrates Mesa's fine-grained reactivity through a professional-grade todo dashboard with advanced features including priority management, categorization, real-time search, analytics, and more.

🚀 Live Interactive Playground

Experience the full power of Mesa's reactivity with our feature-rich todo dashboard:

The playground features a complete task management system with:

  • Priority-based organization (High/Medium/Low)
  • Category management with filtering
  • Real-time search across tasks and categories
  • Analytics dashboard with progress tracking
  • Advanced filtering by status, priority, and category
  • Inline editing with keyboard shortcuts
  • Due date management and overdue indicators

Key Features Demonstrated

Priority Management System

interface Todo {
  id: number;
  text: string;
  completed: boolean;
  priority: "high" | "medium" | "low";
  category: string;
  createdAt: string;
  dueDate?: string;
}

// Priority-based styling and behavior
const PRIORITY_CONFIG = {
  high: {
    color: "text-red-500 bg-red-50 border-red-200",
    icon: Star,
  },
  medium: {
    color: "text-yellow-500 bg-yellow-50 border-yellow-200",
    icon: Clock,
  },
  low: {
    color: "text-green-500 bg-green-50 border-green-200",
    icon: Target,
  },
};

Category Organization

const CATEGORIES = ["General", "Learning", "Development", "Review", "Documentation", "Meeting"];

// Category-based filtering
const filteredTodos = todos.filter((todo) => categoryFilter === "all" || todo.category === categoryFilter);

Real-time Search & Filtering

const todoState = proxy({
  searchQuery: "",
  filter: "all", // 'all', 'active', 'completed'
  priorityFilter: "all", // 'all', 'high', 'medium', 'low'
  categoryFilter: "all",
});

// Multi-dimensional filtering
const filteredTodos = useMemo(() => {
  return todos.filter((todo) => {
    const matchesStatus =
      filter === "all" || (filter === "active" && !todo.completed) || (filter === "completed" && todo.completed);

    const matchesPriority = priorityFilter === "all" || todo.priority === priorityFilter;

    const matchesCategory = categoryFilter === "all" || todo.category === categoryFilter;

    const matchesSearch =
      searchQuery === "" ||
      todo.text.toLowerCase().includes(searchQuery.toLowerCase()) ||
      todo.category.toLowerCase().includes(searchQuery.toLowerCase());

    return matchesStatus && matchesPriority && matchesCategory && matchesSearch;
  });
}, [todos, filter, priorityFilter, categoryFilter, searchQuery]);

Analytics Dashboard

function AnalyticsPanel() {
  const todos = useStore(todoState, (s) => s.todos);

  const analytics = useMemo(() => {
    const total = todos.length;
    const completed = todos.filter((t) => t.completed).length;

    // Category distribution
    const categories = todos.reduce((acc, todo) => {
      acc[todo.category] = (acc[todo.category] || 0) + 1;
      return acc;
    }, {});

    // Active tasks by priority
    const priorities = todos.reduce((acc, todo) => {
      if (!todo.completed) {
        acc[todo.priority] = (acc[todo.priority] || 0) + 1;
      }
      return acc;
    }, {});

    return { total, completed, categories, priorities };
  }, [todos]);

  return <div className="analytics-panel">{/* Progress tracking, priority breakdown, category stats */}</div>;
}

Inline Editing System

function TodoItem({ todo }) {
  const [isEditing, setIsEditing] = useState(false);
  const [editText, setEditText] = useState(todo.text);

  const saveEdit = () => {
    const index = todoState.todos.findIndex((t) => t.id === todo.id);
    if (index !== -1 && editText.trim()) {
      todoState.todos[index].text = editText.trim();
      setIsEditing(false);
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === "Enter") saveEdit();
    if (e.key === "Escape") {
      setIsEditing(false);
      setEditText(todo.text);
    }
  };

  return (
    <div className="todo-item">
      {isEditing ? (
        <input value={editText} onChange={(e) => setEditText(e.target.value)} onKeyDown={handleKeyDown} autoFocus />
      ) : (
        <p onClick={() => setIsEditing(true)}>{todo.text}</p>
      )}
    </div>
  );
}

Mesa's Fine-Grained Reactivity in Action

Surgical Updates

Watch how Mesa updates only the specific components affected by each change:

  1. Toggle Todo Completion

    // Only the specific TodoItem re-renders
    todoState.todos[index].completed = !todoState.todos[index].completed;
    
  2. Update Search Query

    // Only TodoList re-renders to show filtered results
    todoState.searchQuery = "new search";
    
  3. Change Priority Filter

    // Only filter controls and TodoList re-render
    todoState.priorityFilter = "high";
    
  4. Edit Todo Text

    // Only the specific TodoItem being edited re-renders
    todoState.todos[0].text = "Updated text";
    
  5. Add New Todo

    // Only AddTodo form, TodoList, and Analytics re-render
    todoState.todos.push(newTodo);
    

Performance Benefits

The dashboard handles complex state with multiple interconnected components:

  • 12+ reactive components working independently
  • Multi-dimensional filtering without performance loss
  • Real-time analytics that update only when needed
  • Instant search across hundreds of todos
  • Complex nested state with surgical updates

Live Code Example

Here's a simplified version you can experiment with:

import React, { useState } from "react";
import { proxy, useStore } from "mesa-react";

// Professional todo state
const todoState = proxy({
  todos: [
    {
      id: 1,
      text: "Master Mesa's fine-grained reactivity",
      completed: false,
      priority: "high",
      category: "Learning",
    },
    {
      id: 2,
      text: "Build production-ready dashboard",
      completed: false,
      priority: "medium",
      category: "Development",
    },
    {
      id: 3,
      text: "Write comprehensive documentation",
      completed: true,
      priority: "low",
      category: "Documentation",
    },
  ],
  searchQuery: "",
  filter: "all",
  priorityFilter: "all",
});

// Priority configuration
const PRIORITY_CONFIG = {
  high: { color: "#ef4444", label: "🔥 High" },
  medium: { color: "#f59e0b", label: "⚡ Medium" },
  low: { color: "#10b981", label: "🎯 Low" },
};

function SearchBar() {
  const searchQuery = useStore(todoState, (s) => s.searchQuery);

  return (
    <div style={{ marginBottom: "16px" }}>
      <input
        type="text"
        placeholder="🔍 Search todos..."
        value={searchQuery}
        onChange={(e) => (todoState.searchQuery = e.target.value)}
        style={{
          width: "100%",
          padding: "12px 16px",
          border: "2px solid #e5e7eb",
          borderRadius: "8px",
          fontSize: "14px",
        }}
      />
    </div>
  );
}

function FilterControls() {
  const filter = useStore(todoState, (s) => s.filter);
  const priorityFilter = useStore(todoState, (s) => s.priorityFilter);

  return (
    <div
      style={{
        display: "flex",
        gap: "12px",
        marginBottom: "20px",
        flexWrap: "wrap",
      }}
    >
      <div style={{ display: "flex", gap: "4px" }}>
        {["all", "active", "completed"].map((f) => (
          <button
            key={f}
            onClick={() => (todoState.filter = f)}
            style={{
              padding: "6px 12px",
              border: "1px solid #d1d5db",
              borderRadius: "6px",
              background: filter === f ? "#3b82f6" : "white",
              color: filter === f ? "white" : "#374151",
              fontSize: "12px",
              cursor: "pointer",
            }}
          >
            {f.charAt(0).toUpperCase() + f.slice(1)}
          </button>
        ))}
      </div>

      <div style={{ display: "flex", gap: "4px" }}>
        {["all", "high", "medium", "low"].map((p) => (
          <button
            key={p}
            onClick={() => (todoState.priorityFilter = p)}
            style={{
              padding: "6px 12px",
              border: "1px solid #d1d5db",
              borderRadius: "6px",
              background: priorityFilter === p ? "#8b5cf6" : "white",
              color: priorityFilter === p ? "white" : "#374151",
              fontSize: "12px",
              cursor: "pointer",
            }}
          >
            {p === "all" ? "All Priority" : PRIORITY_CONFIG[p]?.label || p}
          </button>
        ))}
      </div>
    </div>
  );
}

function TodoStats() {
  const todos = useStore(todoState, (s) => s.todos);

  const stats = React.useMemo(() => {
    const total = todos.length;
    const completed = todos.filter((t) => t.completed).length;
    const active = total - completed;
    const progress = total === 0 ? 0 : Math.round((completed / total) * 100);

    return { total, completed, active, progress };
  }, [todos]);

  return (
    <div
      style={{
        display: "flex",
        gap: "16px",
        padding: "16px",
        background: "#f8fafc",
        borderRadius: "8px",
        marginBottom: "20px",
      }}
    >
      <div style={{ textAlign: "center" }}>
        <div style={{ fontSize: "24px", fontWeight: "bold", color: "#1f2937" }}>{stats.total}</div>
        <div style={{ fontSize: "12px", color: "#6b7280" }}>Total</div>
      </div>
      <div style={{ textAlign: "center" }}>
        <div style={{ fontSize: "24px", fontWeight: "bold", color: "#3b82f6" }}>{stats.active}</div>
        <div style={{ fontSize: "12px", color: "#6b7280" }}>Active</div>
      </div>
      <div style={{ textAlign: "center" }}>
        <div style={{ fontSize: "24px", fontWeight: "bold", color: "#10b981" }}>{stats.completed}</div>
        <div style={{ fontSize: "12px", color: "#6b7280" }}>Done</div>
      </div>
      <div style={{ textAlign: "center" }}>
        <div style={{ fontSize: "24px", fontWeight: "bold", color: "#8b5cf6" }}>{stats.progress}%</div>
        <div style={{ fontSize: "12px", color: "#6b7280" }}>Progress</div>
      </div>
    </div>
  );
}

function TodoItem({ todo }) {
  const [isEditing, setIsEditing] = useState(false);
  const [editText, setEditText] = useState(todo.text);

  const toggleComplete = () => {
    const index = todoState.todos.findIndex((t) => t.id === todo.id);
    if (index !== -1) {
      todoState.todos[index].completed = !todoState.todos[index].completed;
    }
  };

  const saveEdit = () => {
    const index = todoState.todos.findIndex((t) => t.id === todo.id);
    if (index !== -1 && editText.trim()) {
      todoState.todos[index].text = editText.trim();
      setIsEditing(false);
    }
  };

  const deleteTodo = () => {
    todoState.todos = todoState.todos.filter((t) => t.id !== todo.id);
  };

  const priorityConfig = PRIORITY_CONFIG[todo.priority];

  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        gap: "12px",
        padding: "16px",
        border: "1px solid #e5e7eb",
        borderRadius: "8px",
        marginBottom: "8px",
        background: todo.completed ? "#f9fafb" : "white",
        opacity: todo.completed ? 0.7 : 1,
      }}
    >
      <input type="checkbox" checked={todo.completed} onChange={toggleComplete} style={{ cursor: "pointer" }} />

      {isEditing ? (
        <input
          type="text"
          value={editText}
          onChange={(e) => setEditText(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter") saveEdit();
            if (e.key === "Escape") {
              setIsEditing(false);
              setEditText(todo.text);
            }
          }}
          onBlur={saveEdit}
          autoFocus
          style={{
            flex: 1,
            padding: "4px 8px",
            border: "1px solid #3b82f6",
            borderRadius: "4px",
          }}
        />
      ) : (
        <span
          onClick={() => setIsEditing(true)}
          style={{
            flex: 1,
            cursor: "pointer",
            textDecoration: todo.completed ? "line-through" : "none",
            color: todo.completed ? "#9ca3af" : "#1f2937",
          }}
        >
          {todo.text}
        </span>
      )}

      <span
        style={{
          padding: "4px 8px",
          borderRadius: "12px",
          background: priorityConfig.color,
          color: "white",
          fontSize: "11px",
          fontWeight: "bold",
        }}
      >
        {priorityConfig.label}
      </span>

      <span
        style={{
          padding: "2px 6px",
          background: "#e5e7eb",
          color: "#6b7280",
          borderRadius: "4px",
          fontSize: "10px",
        }}
      >
        {todo.category}
      </span>

      <button
        onClick={deleteTodo}
        style={{
          background: "#ef4444",
          color: "white",
          border: "none",
          borderRadius: "4px",
          padding: "4px 8px",
          cursor: "pointer",
          fontSize: "12px",
        }}
      >
      </button>
    </div>
  );
}

function TodoList() {
  const todos = useStore(todoState, (s) => s.todos);
  const filter = useStore(todoState, (s) => s.filter);
  const priorityFilter = useStore(todoState, (s) => s.priorityFilter);
  const searchQuery = useStore(todoState, (s) => s.searchQuery);

  const filteredTodos = React.useMemo(() => {
    return todos.filter((todo) => {
      const matchesStatus =
        filter === "all" || (filter === "active" && !todo.completed) || (filter === "completed" && todo.completed);

      const matchesPriority = priorityFilter === "all" || todo.priority === priorityFilter;

      const matchesSearch =
        searchQuery === "" ||
        todo.text.toLowerCase().includes(searchQuery.toLowerCase()) ||
        todo.category.toLowerCase().includes(searchQuery.toLowerCase());

      return matchesStatus && matchesPriority && matchesSearch;
    });
  }, [todos, filter, priorityFilter, searchQuery]);

  return (
    <div>
      {filteredTodos.length === 0 ? (
        <div
          style={{
            textAlign: "center",
            padding: "40px",
            color: "#6b7280",
            fontSize: "14px",
          }}
        >
          {searchQuery ? "No todos match your search" : "No todos found"}
        </div>
      ) : (
        filteredTodos.map((todo) => <TodoItem key={todo.id} todo={todo} />)
      )}
    </div>
  );
}

function AddTodo() {
  const [newTodo, setNewTodo] = useState("");
  const [priority, setPriority] = useState("medium");
  const [category, setCategory] = useState("General");

  const addTodo = () => {
    if (newTodo.trim()) {
      todoState.todos.push({
        id: Date.now(),
        text: newTodo.trim(),
        completed: false,
        priority,
        category,
      });
      setNewTodo("");
    }
  };

  return (
    <div
      style={{
        display: "flex",
        gap: "8px",
        marginBottom: "20px",
        padding: "16px",
        background: "#f8fafc",
        borderRadius: "8px",
      }}
    >
      <input
        type="text"
        value={newTodo}
        onChange={(e) => setNewTodo(e.target.value)}
        onKeyDown={(e) => e.key === "Enter" && addTodo()}
        placeholder="Add a new todo..."
        style={{
          flex: 1,
          padding: "8px 12px",
          border: "1px solid #d1d5db",
          borderRadius: "6px",
        }}
      />

      <select
        value={priority}
        onChange={(e) => setPriority(e.target.value)}
        style={{
          padding: "8px 12px",
          border: "1px solid #d1d5db",
          borderRadius: "6px",
        }}
      >
        <option value="low">Low Priority</option>
        <option value="medium">Medium Priority</option>
        <option value="high">High Priority</option>
      </select>

      <select
        value={category}
        onChange={(e) => setCategory(e.target.value)}
        style={{
          padding: "8px 12px",
          border: "1px solid #d1d5db",
          borderRadius: "6px",
        }}
      >
        {["General", "Learning", "Development", "Review", "Documentation"].map((cat) => (
          <option key={cat} value={cat}>
            {cat}
          </option>
        ))}
      </select>

      <button
        onClick={addTodo}
        disabled={!newTodo.trim()}
        style={{
          padding: "8px 16px",
          background: newTodo.trim() ? "#3b82f6" : "#9ca3af",
          color: "white",
          border: "none",
          borderRadius: "6px",
          cursor: newTodo.trim() ? "pointer" : "not-allowed",
        }}
      >
        Add Todo
      </button>
    </div>
  );
}

// Main app
function TodoApp() {
  return (
    <div
      style={{
        maxWidth: "800px",
        margin: "0 auto",
        padding: "20px",
        fontFamily: "system-ui, sans-serif",
      }}
    >
      <div
        style={{
          textAlign: "center",
          marginBottom: "24px",
          padding: "24px",
          background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
          color: "white",
          borderRadius: "12px",
        }}
      >
        <h1 style={{ margin: "0 0 8px 0", fontSize: "28px" }}>Mesa Professional Todo Dashboard</h1>
        <p style={{ margin: 0, opacity: 0.9 }}>Experience fine-grained reactivity with advanced task management</p>
      </div>

      <TodoStats />
      <SearchBar />
      <FilterControls />
      <AddTodo />
      <TodoList />
    </div>
  );
}

export default TodoApp;

Architecture Highlights

Component Structure

TodoDashboard
├── DashboardHeader (stats, progress circle)
├── LeftSidebar
│   ├── AddTodo (form with priority/category)
│   └── AnalyticsPanel (charts, breakdowns)
└── MainContent
    ├── SearchAndFilters (multi-dimensional)
    └── TodoList (filtered, sortable items)
        └── TodoItem[] (inline editing, actions)

UI/UX Features

  • Responsive design that works on mobile and desktop
  • Dark/light theme support with system preference detection
  • Keyboard shortcuts for common actions (Enter, Escape, etc.)
  • Visual feedback for all interactions
  • Progress indicators and completion animations
  • Priority color coding throughout the interface
  • Accessible with proper ARIA labels and semantic HTML

Performance Optimizations

  • Fine-grained subscriptions - components only re-render when their specific data changes
  • Computed selectors - analytics update only when underlying todos change
  • Debounced search - search queries don't trigger excessive re-renders
  • Virtual scrolling ready - architecture supports large todo lists
  • Optimistic updates - UI updates immediately, no loading states needed

Advanced Implementation Patterns

1. Multi-level State Organization

const todoState = proxy({
  // Data layer
  todos: [],

  // UI state layer
  filters: {
    status: "all",
    priority: "all",
    category: "all",
    search: "",
  },

  // Form state layer
  forms: {
    newTodo: {
      text: "",
      priority: "medium",
      category: "General",
    },
  },

  // UI preferences
  ui: {
    viewMode: "list", // or "grid"
    sortBy: "createdAt",
    sortOrder: "desc",
  },
});

2. Derived State with useMemo

function TodoAnalytics() {
  const todos = useStore(todoState, (s) => s.todos);

  // This only recalculates when todos array changes
  const analytics = useMemo(() => {
    const now = new Date();
    const total = todos.length;
    const completed = todos.filter((t) => t.completed).length;

    // Complex calculations...
    const overdue = todos.filter((t) => t.dueDate && new Date(t.dueDate) < now && !t.completed).length;

    const categoryStats = todos.reduce((acc, todo) => {
      const cat = todo.category;
      acc[cat] = acc[cat] || { total: 0, completed: 0 };
      acc[cat].total++;
      if (todo.completed) acc[cat].completed++;
      return acc;
    }, {});

    return {
      total,
      completed,
      active: total - completed,
      overdue,
      completionRate: total ? Math.round((completed / total) * 100) : 0,
      categoryStats,
    };
  }, [todos]);

  return <AnalyticsDashboard data={analytics} />;
}

3. Custom Hooks for Complex Logic

function useTodoFilters() {
  const todos = useStore(todoState, (s) => s.todos);
  const filters = useStore(todoState, (s) => s.filters);

  return useMemo(() => {
    return todos.filter((todo) => {
      // Status filter
      if (filters.status !== "all") {
        if (filters.status === "active" && todo.completed) return false;
        if (filters.status === "completed" && !todo.completed) return false;
      }

      // Priority filter
      if (filters.priority !== "all" && todo.priority !== filters.priority) {
        return false;
      }

      // Category filter
      if (filters.category !== "all" && todo.category !== filters.category) {
        return false;
      }

      // Search filter
      if (filters.search) {
        const query = filters.search.toLowerCase();
        return todo.text.toLowerCase().includes(query) || todo.category.toLowerCase().includes(query);
      }

      return true;
    });
  }, [todos, filters]);
}

Testing Strategies

Unit Testing with Mesa

import { render, screen, fireEvent } from "@testing-library/react";
import { proxy } from "mesa-react";

describe("Professional Todo Dashboard", () => {
  let testState;

  beforeEach(() => {
    testState = proxy({
      todos: [
        {
          id: 1,
          text: "Test todo",
          completed: false,
          priority: "high",
          category: "Testing",
        },
      ],
      filters: { status: "all", priority: "all", category: "all", search: "" },
    });
  });

  test("filters todos by priority", () => {
    testState.filters.priority = "high";

    // Test that only high priority todos are shown
    expect(getFilteredTodos(testState)).toHaveLength(1);

    testState.filters.priority = "low";
    expect(getFilteredTodos(testState)).toHaveLength(0);
  });

  test("search works across text and categories", () => {
    testState.filters.search = "test";
    expect(getFilteredTodos(testState)).toHaveLength(1);

    testState.filters.search = "Testing";
    expect(getFilteredTodos(testState)).toHaveLength(1);

    testState.filters.search = "nonexistent";
    expect(getFilteredTodos(testState)).toHaveLength(0);
  });
});

This professional todo dashboard showcases Mesa's ability to handle complex, real-world applications with multiple interconnected features while maintaining optimal performance through fine-grained reactivity.

Data Initialization with useInitSync

For real-world applications, you'll often need to initialize your todo list with data from APIs, localStorage, or user preferences. Here's how to enhance the todo dashboard with useInitSync:

import { proxy, useStore, useInitSync } from "mesa-react";

// Enhanced todo state with initialization support
const enhancedTodoState = proxy({
  todos: [],
  categories: [],
  userPreferences: {
    theme: "light",
    defaultPriority: "medium",
    defaultCategory: "General",
    viewMode: "list",
  },
  filters: {
    status: "all",
    priority: "all", 
    category: "all",
    search: "",
  },
  loading: true,
  error: null,
  initialized: false,
});

// Mock API functions
const fetchUserTodos = async (userId) => {
  // Simulate API call
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        {
          id: 1,
          text: "Review quarterly performance metrics",
          completed: false,
          priority: "high",
          category: "Work",
          createdAt: "2024-01-10",
          dueDate: "2024-01-15",
        },
        {
          id: 2,
          text: "Complete React hooks tutorial",
          completed: true,
          priority: "medium", 
          category: "Learning",
          createdAt: "2024-01-08",
        },
        {
          id: 3,
          text: "Update project documentation",
          completed: false,
          priority: "low",
          category: "Documentation", 
          createdAt: "2024-01-12",
          dueDate: "2024-01-20",
        },
      ]);
    }, 800);
  });
};

const fetchUserPreferences = async (userId) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        theme: "dark",
        defaultPriority: "medium",
        defaultCategory: "Work",
        viewMode: "grid",
        savedFilters: {
          status: "active",
          priority: "all",
          category: "Work",
        }
      });
    }, 500);
  });
};

const fetchAvailableCategories = async () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        "General",
        "Work", 
        "Learning",
        "Personal",
        "Health",
        "Documentation",
        "Meeting",
        "Shopping"
      ]);
    }, 300);
  });
};

// Enhanced TodoApp with initialization
function EnhancedTodoApp({ userId = "user123" }) {
  // Initialize all todo data and user preferences
  const { error, refetch } = useInitSync(enhancedTodoState, async (state) => {
    state.loading = true;
    state.error = null;

    try {
      // Load data in parallel for better performance
      const [todos, preferences, categories] = await Promise.all([
        fetchUserTodos(userId),
        fetchUserPreferences(userId),
        fetchAvailableCategories(),
      ]);

      // Update state atomically
      state.todos = todos;
      state.userPreferences = preferences;
      state.categories = categories;
      
      // Apply saved filter preferences
      if (preferences.savedFilters) {
        state.filters = { ...state.filters, ...preferences.savedFilters };
      }
      
      state.initialized = true;
      
    } catch (error) {
      state.error = error.message;
      console.error("Failed to initialize todo app:", error);
    } finally {
      state.loading = false;
    }
  }, {
    deps: [userId], // Re-initialize when user changes
    onSuccess: () => {
      console.log("Todo app initialized successfully");
    },
    onError: (error) => {
      console.error("Todo initialization failed:", error);
    }
  });

  const { loading, initialized, error: initError } = useStore(enhancedTodoState, s => ({
    loading: s.loading,
    initialized: s.initialized,
    error: s.error
  }));

  if (loading && !initialized) {
    return <TodoLoadingSkeleton />;
  }

  if (initError) {
    return <TodoErrorDisplay error={initError} onRetry={refetch} />;
  }

  return (
    <div className="enhanced-todo-app">
      <TodoHeader />
      <div className="todo-layout">
        <TodoSidebar />
        <TodoMainContent />
      </div>
    </div>
  );
}

// Loading skeleton for todos
function TodoLoadingSkeleton() {
  return (
    <div className="todo-skeleton">
      <div className="skeleton-header">
        <div className="skeleton-line skeleton-title"></div>
        <div className="skeleton-line skeleton-subtitle"></div>
      </div>
      
      <div className="skeleton-stats">
        {[...Array(3)].map((_, i) => (
          <div key={i} className="skeleton-stat-card"></div>
        ))}
      </div>
      
      <div className="skeleton-todos">
        {[...Array(5)].map((_, i) => (
          <div key={i} className="skeleton-todo-item">
            <div className="skeleton-checkbox"></div>
            <div className="skeleton-text"></div>
            <div className="skeleton-badge"></div>
          </div>
        ))}
      </div>
      
      <style jsx>{`
        .skeleton-line, .skeleton-stat-card, .skeleton-todo-item > div {
          background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
          background-size: 200% 100%;
          animation: skeleton-loading 1.5s infinite;
        }
        
        @keyframes skeleton-loading {
          0% { background-position: 200% 0; }
          100% { background-position: -200% 0; }
        }
      `}</style>
    </div>
  );
}

// Error display component
function TodoErrorDisplay({ error, onRetry }) {
  return (
    <div className="todo-error">
      <div className="error-content">
        <div className="error-icon">⚠️</div>
        <h2>Failed to Load Todos</h2>
        <p>{error}</p>
        <div className="error-actions">
          <button onClick={onRetry} className="retry-button">
            Try Again
          </button>
          <button onClick={() => window.location.reload()} className="refresh-button">
            Refresh Page
          </button>
        </div>
      </div>
    </div>
  );
}

// Enhanced components with access to initialized data
function TodoHeader() {
  const { userPreferences, todos } = useStore(enhancedTodoState, s => ({
    userPreferences: s.userPreferences,
    todos: s.todos
  }));

  const completedCount = todos.filter(t => t.completed).length;
  const completionRate = todos.length > 0 ? Math.round((completedCount / todos.length) * 100) : 0;

  return (
    <header className={`todo-header theme-${userPreferences.theme}`}>
      <h1>My Todo Dashboard</h1>
      <div className="progress-indicator">
        <div className="progress-circle">
          <span>{completionRate}%</span>
        </div>
        <div className="progress-stats">
          <p>{completedCount} of {todos.length} completed</p>
        </div>
      </div>
    </header>
  );
}

function TodoSidebar() {
  const categories = useStore(enhancedTodoState, s => s.categories);
  const userPreferences = useStore(enhancedTodoState, s => s.userPreferences);

  return (
    <aside className="todo-sidebar">
      <AddTodoForm categories={categories} defaultCategory={userPreferences.defaultCategory} />
      <TodoAnalytics />
      <CategoryFilter categories={categories} />
    </aside>
  );
}

function AddTodoForm({ categories, defaultCategory }) {
  const [newTodo, setNewTodo] = useState("");
  const [priority, setPriority] = useState("medium");
  const [category, setCategory] = useState(defaultCategory);
  
  const addTodo = () => {
    if (newTodo.trim()) {
      enhancedTodoState.todos.push({
        id: Date.now(),
        text: newTodo.trim(),
        completed: false,
        priority,
        category,
        createdAt: new Date().toISOString(),
      });
      setNewTodo("");
      
      // Save to backend/localStorage
      saveTodoChanges();
    }
  };

  return (
    <form className="add-todo-form" onSubmit={(e) => { e.preventDefault(); addTodo(); }}>
      <input
        type="text"
        value={newTodo}
        onChange={(e) => setNewTodo(e.target.value)}
        placeholder="Add a new todo..."
        className="todo-input"
      />
      
      <div className="todo-form-controls">
        <select value={priority} onChange={(e) => setPriority(e.target.value)}>
          <option value="low">Low Priority</option>
          <option value="medium">Medium Priority</option>
          <option value="high">High Priority</option>
        </select>
        
        <select value={category} onChange={(e) => setCategory(e.target.value)}>
          {categories.map(cat => (
            <option key={cat} value={cat}>{cat}</option>
          ))}
        </select>
      </div>
      
      <button type="submit" disabled={!newTodo.trim()}>
        Add Todo
      </button>
    </form>
  );
}

// Helper function to persist changes
const saveTodoChanges = async () => {
  try {
    // In a real app, this would save to your backend
    const dataToSave = {
      todos: enhancedTodoState.todos,
      filters: enhancedTodoState.filters,
      userPreferences: enhancedTodoState.userPreferences,
    };
    
    localStorage.setItem('enhanced-todos', JSON.stringify(dataToSave));
    
    // Optionally sync with backend
    // await fetch('/api/todos', { method: 'PUT', body: JSON.stringify(dataToSave) });
    
  } catch (error) {
    console.error('Failed to save todo changes:', error);
  }
};

Key Initialization Patterns

1. Parallel Data Loading

// Load all required data sources concurrently
const [todos, preferences, categories] = await Promise.all([
  fetchUserTodos(userId),
  fetchUserPreferences(userId), 
  fetchAvailableCategories(),
]);

2. Progressive Enhancement

useInitSync(todoState, async (state) => {
  // Load critical data first
  state.todos = await fetchUserTodos(userId);
  state.initialized = true; // App is usable
  
  // Load enhancements in background
  const preferences = await fetchUserPreferences(userId);
  state.userPreferences = preferences;
});

3. Offline-First with Fallbacks

useInitSync(todoState, async (state) => {
  try {
    // Try to load from server first
    const serverTodos = await fetchUserTodos(userId);
    state.todos = serverTodos;
    
    // Cache for offline use
    localStorage.setItem('todos-cache', JSON.stringify(serverTodos));
  } catch (error) {
    // Fall back to cached data
    const cachedTodos = JSON.parse(localStorage.getItem('todos-cache') || '[]');
    state.todos = cachedTodos;
    
    // Show offline indicator
    state.isOffline = true;
  }
});

4. User-Specific Initialization

function TodoApp({ userId }) {
  useInitSync(todoState, async (state) => {
    if (!userId) {
      // Guest user - load sample todos
      state.todos = getSampleTodos();
      state.userPreferences = getDefaultPreferences();
      return;
    }
    
    // Authenticated user - load their data
    const [todos, prefs] = await Promise.all([
      fetchUserTodos(userId),
      fetchUserPreferences(userId)
    ]);
    
    state.todos = todos;
    state.userPreferences = prefs;
  }, {
    deps: [userId] // Re-run when user changes
  });
}

Benefits of Todo Initialization

  1. Seamless User Experience: Data loads transparently while showing appropriate loading states
  2. Personalization: User preferences and saved filters are automatically applied
  3. Performance: Parallel data loading reduces initial load time
  4. Offline Capability: Graceful fallbacks to cached data when network is unavailable
  5. Error Recovery: Clear error states with retry functionality

See Also