Skip to content

The Reactive Core: $( )

The $ function is the heart of SigPro. It is a Unified Reactive Constructor that handles state, derivations, and automatic persistence through a single, consistent interface.

1. The Constructor: $( input, [key] )

Depending on the arguments you pass, SigPro creates different reactive primitives:

ArgumentTypeRequiredDescription
inputValue / FunctionYesInitial state or reactive logic.
keystringNoIf provided, the signal persists in localStorage.

2. Signal (State & Persistence)

A Signal is a reactive "box" for data. SigPro now supports Native Persistence: if you provide a second argument (the key), the signal will automatically sync with localStorage.

  • Standard: const $count = $(0);
  • Persistent: const $theme = $("light", "app-theme"); (Restores value on page reload).

Example:

javascript
const $user = $("Guest", "session-user"); // Automatically saved/loaded

// Read (Getter)
console.log($user()); 

// Update (Setter + Auto-save to Disk)
$user("Alice"); 

// Functional Update
$user(prev => prev.toUpperCase());

3. Computed (Derived State)

When you pass a function that returns a value, SigPro creates a Computed Signal. It tracks dependencies and recalculates only when necessary.

  • Syntax: const $derived = $(() => logic);

Example:

javascript
const $price = $(100);
const $qty = $(2);

// Auto-tracks $price and $qty
const $total = $(() => $price() * $qty());

$qty(3); // $total updates to 300 automatically

4. Effects (Reactive Actions)

An Effect is a function that does not return a value. It performs an action (side effect) whenever the signals it "touches" change.

  • When to use: Logging, manual DOM tweaks, or syncing with external APIs.
  • Syntax: $(() => { action });

Example:

javascript
const $status = $("online");

// Runs every time $status changes
$(() => {
  console.log("System status is now:", $status());
});

5. Summary Table: Usage Guide

PrimitiveLogic TypePersistence?Typical Use Case
SignalMutable StateYes (Optional)$(0, 'counter')
ComputedDerived / Read-onlyNo$(() => $a() + $b())
EffectImperative ActionNo$(() => alert($msg()))

💡 Pro Tip: The Power of Native Persistence

In SigPro, you don't need external plugins for basic storage. By using the key parameter in a Signal, you gain:

  1. Zero Boilerplate: No more JSON.parse(localStorage.getItem(...)).
  2. Instant Hydration: The value is restored before the UI renders, preventing "flicker".
  3. Atomic Safety: Data is saved to disk exactly when the signal changes, ensuring your app state is always safe.

Naming Convention

We use the $ prefix (e.g., $count) for reactive functions to distinguish them from static variables at a glance:

javascript
let count = 0;       // Static
const $count = $(0); // Reactive Signal