Skip to content

🚧 Under Construction 🚧

This site is currently under construction. This page is generated by AI and has not undergone thorough review by a human. There may be hallucination!

In fact, for now only /, /reactive, and the llms.txt are carefully crafted by myself.

Derived

A derived value is a calculation based on one or more signals. It's both lazy and cached.

  • Lazy: The calculation only runs when you ask for its value (i.e., when it's "pulled").
  • Cached: If its underlying signals haven't changed, the derived value won't re-run the calculation. It will return a cached result.

When a signal dependency changes, the derived value is marked as "stale." The expensive calculation isn't performed immediately; it waits until the next time the value is requested. This is different from an effect, which runs immediately when its dependencies change, and is meant for side effects, not for returning values.

from reactivity import signal, derived, memoized, effect

derived is for lazy, pull-based computations. It only re-calculates when its value is requested.

memoized is for cached computations with dependency tracking. It caches results and invalidates them when dependencies change, recomputing only when accessed.

Example

from reactivity import signal, derived

s = signal(0)

@derived
def f():
    print("expensive computing ...")
    return s.get() * 2

Unlike effect which runs immediately when declared, nothing will happen until you call f():

print(f())
# expensive computing ...
# 0
print(f())
# 0

Multiple calls won't re-run, but will return the cached value. Because when the data source is unchanged, idempotent data pipelines should return the same result.

But if you call s.set(...) and then call f() again, f will re-run once:

s.set(1)
print(f())
# expensive computing ...
# 2
print(f())
# 2

Tips

  • derived for lazy computed values; memoized for cached computations that track dependencies
  • Both integrate with batch() and contexts
  • Use async_derived for async computations
  • Unlike effects, derived values are about returning processed data, not performing side effects

See Also