Values that auto-update when their dependencies change. No manual tracking needed!
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!
Because manual calculations are error-prone and annoying!
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!
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!
const [width, setWidth] = useSignal(10); const [height, setHeight] = useSignal(5);
const area = createComputed(() => width * height); // ↑ // Your calculation here!
const areaValue = useSignalValue(area);
<div>Area: {areaValue}</div> // Always correct! ✨🧮 Try changing the rectangle size below to see it in action! ⬇️
Move the sliders - watch ALL 3 calculations update automatically without ANY extra code!
const [width, setWidth] = useSignal(10);
const [height, setHeight] = useSignal(5);const area = createComputed(() => width * height);💡 SignalForge automatically tracks that this depends on width and height!
const areaValue = useSignalValue(area); // 50
setWidth(20); // area recalculates automatically! ✨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 boilerplatetotal = sum(items.map(i => i.price * i.qty))avgRevenue = totalRevenue / daysCountisValid = email.valid && password.length > 8score = kills * 100 + bonuses - penalties