core / const

derive

Creates a read-only derived signal computed from other signals.

Source: src/_core/derive.ts

Creates a read-only derived signal computed from other signals.

The derived signal's value is computed by the provided function, which should access .value on signals to establish dependencies. The value is recomputed whenever any tracked dependency changes.

Signature

export const derive = <T>(
  valueGetterFn: DerivedValueGetterWithSignals<T>,
): DerivedSignal<T> => {
  let oldValue: T | undefined;
  let currValue: T | undefined;
  const derivedSource = signal<T>(oldValue as T);
  const derivedSourceUpdator = effect(() => {
    oldValue = currValue;
    currValue = valueGetterFn(oldValue);
    derivedSource.value = currValue;
  });

  const derivedSignal: DerivedSignal<T> = {
    type: "derived-signal",
    get prevValue() {
      return oldValue;
    },
    get value() {
      return derivedSource.value;
    },
    dispose() {
      derivedSourceUpdator.dispose();
    },
  };

  return derivedSignal;
};

Type Parameters

  • The type of value the derived signal holds

Parameters

Receives the previous computed value (undefined on first run).

  • valueGetterFn: A function that computes the derived value.

Returns

A derived signal with value, prevValue, and dispose() methods

Remarks

  • Dependencies are only tracked for signals whose .value is accessed during execution
  • If a signal is accessed conditionally and the condition is false on first run, it won't be tracked
  • The previous value is undefined on the first computation
  • Derived signals can depend on other derived signals (chaining)

Examples

const count = signal(5);
const doubled = derive(() => count.value * 2);
console.log(doubled.value); // 10

// Using previous value
const history = derive((prev) => {
  const current = count.value;
  return prev ? [...prev, current] : [current];
});

See Also

  • DerivedValueGetterWithSignals - The type of the value getter function
  • signal - For creating mutable source signals
  • effect - For registering functions to run when signal values change