← Back to Home

🧮 Computed Signals - Automatic Calculations

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

What is a Computed Signal?

A computed signal is a value that automatically calculates itself based on other signals. When the inputs change, it recalculates instantly!

💡 Real-life example: Like a spreadsheet formula! When you change A1 or B1, the formula =A1+B1 automatically updates. That's exactly what computed signals do!

💡

Why Use Computed Signals?

Because manual calculations are error-prone and annoying!

❌ Without Computed Signals

const [width, setWidth] = useState(10);
const [height, setHeight] = useState(5);
const [area, setArea] = useState(50);

// Update width
setWidth(20);
setArea(width * height); // FORGOT TO UPDATE!

// Update height  
setHeight(10);
setArea(width * height); // Manual sync again!

// 😱 Easy to forget, causes bugs!

✅ With Computed Signals

const [width, setWidth] = useSignal(10);
const [height, setHeight] = useSignal(5);
const area = createComputed(() => 
  width * height
);

// Update width
setWidth(20); // area auto-updates! ✨

// Update height
setHeight(10); // area auto-updates! ✨

// 🎉 Always in sync, zero effort!
🚀

How To Use It? (Super Simple Pattern!)

1

Create your input signals

const [width, setWidth] = useSignal(10);
const [height, setHeight] = useSignal(5);
2

Create computed signal with a formula

const area = createComputed(() => width * height);
//                          ↑
//                    Your calculation here!
3

Use it - it auto-updates forever!

const areaValue = useSignalValue(area);
<div>Area: {areaValue}</div>  // Always correct! ✨

🧮 Try changing the rectangle size below to see it in action! ⬇️

🎨 Interactive Rectangle Calculator

Move the sliders - watch ALL 3 calculations update automatically without ANY extra code!

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: