Computed vars have values derived from other properties on the backend. They are
defined as methods in your State class with the @rx.var decorator.
Try typing in the input box and clicking out.
HELLO
Here, upper_text is a computed var that always holds the upper case version of text.
We recommend always using type annotations for computed vars.
By default, all computed vars are cached (cache=True). A cached var is only
recomputed when the other state vars it depends on change. This is useful for
expensive computations, but in some cases it may not update when you expect it to.
To create a computed var that recomputes on every state update regardless of
dependencies, use @rx.var(cache=False).
Previous versions of Reflex had a @rx.cached_var decorator, which is now replaced
by the cache argument of @rx.var (which defaults to True).
State touched at: 23:43:04
Counter A: 0 at 23:43:04
Counter B: 0 at 23:43:04
In this example last_touch_time uses cache=False to ensure it updates any
time the state is modified. last_counter_a_update is a cached computed var (using
the default cache=True) that only depends on counter_a, so it only gets recomputed
when counter_a changes. Similarly last_counter_b_update only depends on counter_b,
and thus is updated only when counter_b changes.
Async computed vars allow you to use asynchronous operations in your computed vars.
They are defined as async methods in your State class with the same @rx.var decorator.
Async computed vars are useful for operations that require asynchronous processing, such as:
- Fetching data from external APIs
- Database operations
- File I/O operations
- Any other operations that benefit from async/await
Async Computed Var Example
Count: 0
Delayed count (x2): 0
In this example, delayed_count is an async computed var that returns the count multiplied by 2 after a simulated delay.
When the count changes, the async computed var is automatically recomputed.
Just like regular computed vars, async computed vars can also be cached. This is especially useful for expensive async operations like API calls or database queries.
Cached Async Computed Var Example
User ID: 1
User Name: Alice
User Email: alice@example.com
Note: The cached async var only updates when user_id changes, not when refresh_trigger changes.
In this example, user_data is a cached async computed var that simulates fetching user data.
It is only recomputed when user_id changes, not when other state variables like refresh_trigger change.
This demonstrates how caching works with async computed vars to optimize performance for expensive operations.