withPrevious<T> method

Computed<T> withPrevious<T>(
  1. T getter(
    1. T?
    ), {
  2. JoltDebugFn? onDebug,
})

Creates a computed value hook with a getter that receives the previous value.

The getter function receives the previous computed value (or null on first computation) as a parameter, allowing you to implement custom logic based on the previous state. This is useful for maintaining referential equality, implementing incremental calculations, or optimizing list/map stability.

Parameters:

  • getter: Function that computes the value, receiving the previous value (or null on first computation) as a parameter
  • onDebug: Optional debug callback for reactive system debugging

Returns: A Computed that can access its previous value during computation

Example:

setup(context, props) {
  final signal = useSignal<List<int>>([1, 2, 3]);
  final computed = useComputed.withPrevious<List<int>>((prev) {
    final newList = List<int>.from(signal.value);
    if (prev != null &&
        prev.length == newList.length &&
        prev.every((item) => newList.contains(item))) {
      return prev; // Return previous to maintain stability
    }
    return newList;
  });

  return () => Text('Items: ${computed.value.join(", ")}');
}

Implementation

Computed<T> withPrevious<T>(T Function(T?) getter, {JoltDebugFn? onDebug}) {
  return useAutoDispose(
      () => Computed.withPrevious(getter, onDebug: onDebug));
}