memo

Attribute Macro memo 

Source
#[memo]
Expand description

Turns a zero-argument function into a memoized, reactive computation.

The #[memo] attribute macro transforms a function into a static reactive_cache::Memo, which:

  1. Computes the value the first time the function is called.
  2. Caches the result for future calls.
  3. Automatically tracks reactive dependencies if used inside Signal or other reactive contexts.

§Requirements

  • The function must have no parameters.
  • The function must return a value (-> T), which must implement Clone.

§Examples

use reactive_macros::memo;

#[memo]
pub fn get_number() -> i32 {
    // The first call sets INVOKED to true
    static mut INVOKED: bool = false;
    assert!(!unsafe { INVOKED });
    unsafe { INVOKED = true };

    42
}

fn main() {
    // First call computes and caches the value
    assert_eq!(get_number(), 42);
    // Subsequent calls return the cached value without re-running the block
    assert_eq!(get_number(), 42);
}

§SAFETY

This macro uses a static mut internally, so it is not thread-safe. It is intended for single-threaded usage only. Accessing the memo from multiple threads concurrently can cause undefined behavior.