Computed Vars

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. A computed var is recomputed every time an event is processed in your app.

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.

Cached Vars

A cached var, decorated as @rx.var(cache=True) is a special type of computed var that 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. Previous versions of Reflex had a @rx.cached_var decorator, which is now replaced by the new cache argument of @rx.var.

State touched at: 04:20:18

Counter A: 0 at 04:20:18

Counter B: 0 at 04:20:18

In this example last_touch_time is a normal computed var, which updates any time the state is modified. last_counter_a_update is a computed var that only depends on counter_a, so it only gets recomputed when counter_a has changes. Similarly last_counter_b_update only depends on counter_b, and thus is updated only when counter_b changes.

Async Computed Vars

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.

Caching Async Computed Vars

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.

Built with Reflex