← Back to Home

🧮 Computed Signals - Automatic Calculations

Values that auto-update when their dependencies change. No manual tracking needed!

📚 What You'll Learn

  • Create computed values with createComputed()
  • Automatically track dependencies (no manual setup!)
  • Build complex calculations from simple signals
  • Avoid recalculating unless dependencies actually change

🎨 Try It: Rectangle Calculator

Change width or height - watch all calculated values update automatically!

10 × 5
50
Area (w × h)
30
Perimeter (2(w+h))
11.18
Diagonal (√(w²+h²))

🚀 How It Works (3 Simple Steps)

Step 1: Create your source signals
const [width, setWidth] = useSignal(10);
const [height, setHeight] = useSignal(5);
Step 2: Create computed signal with a function
const area = createComputed(() => width * height);

💡 SignalForge automatically tracks that this depends on width and height!

Step 3: Use it - updates happen automatically
const areaValue = useSignalValue(area); // 50
setWidth(20); // area recalculates automatically! ✨

💻 Complete Code Example

import { useSignal, createComputed, useSignalValue } from 'signalforge/react';
import { useState } from 'react';

function RectangleCalculator() {
  // Create source signals
  const [width, setWidth] = useSignal(10);
  const [height, setHeight] = useSignal(5);
  
  // Create computed signals - these auto-update!
  const [area] = useState(() => 
    createComputed(() => width * height)
  );
  const [perimeter] = useState(() => 
    createComputed(() => 2 * (width + height))
  );
  
  // Read computed values
  const areaValue = useSignalValue(area);
  const perimeterValue = useSignalValue(perimeter);
  
  return (
    <div>
      <h2>Area: {areaValue}</h2>
      <h2>Perimeter: {perimeterValue}</h2>
      
      <input 
        value={width} 
        onChange={(e) => setWidth(Number(e.target.value))}
      />
      {/* When width changes, area and perimeter 
          automatically recalculate! */}
    </div>
  );
}

// ✨ Benefits:
// • No manual dependency tracking
// • Only recalculates when dependencies change
// • Can chain computed signals together
// • Zero boilerplate

💡 Why Computed Signals Are Better

❌ Traditional useMemo:
  • • Must list all dependencies manually
  • • Easy to forget a dependency
  • • Verbose dependency arrays
  • • Hard to debug stale values
✅ SignalForge Computed:
  • • Auto-tracks dependencies
  • • Impossible to miss dependencies
  • • Clean, simple syntax
  • • Always accurate and up-to-date

🌍 Real-World Use Cases

🛒 Shopping Cart Total
total = sum(items.map(i => i.price * i.qty))
📊 Dashboard Metrics
avgRevenue = totalRevenue / daysCount
✅ Form Validation
isValid = email.valid && password.length > 8
🎮 Game Score
score = kills * 100 + bonuses - penalties

🎓 Next Steps

Master computed signals? Try these next: