Function freya::prelude::use_memo

pub fn use_memo<R>(f: impl FnMut() -> R + 'static) -> Memo<R>
where R: PartialEq,
Expand description

Creates a new Memo. The memo will be run immediately and whenever any signal it reads is written to. Memos can be used to efficiently compute derived data from signals.

use dioxus::prelude::*;
use dioxus_signals::*;

fn App() -> Element {
    let mut count = use_signal(|| 0);
    // the double memo will always be equal to two times the value of count, even after count changes
    let double = use_memo(move || count * 2);

    rsx! {
        "{double}"
        button {
            // When count changes, the memo will rerun and double will be updated
            // memos rerun any time you write to a signal they read. They will only rerun values/component that depend on them if the value of the memo changes
            onclick: move |_| count += 1,
            "Increment"
        }
    }
}

The closure you pass into memos will be called whenever the state you read inside the memo is written to even if the value hasn’t actually changed, but the memo you get will not rerun other parts of your app unless the output changes (PartialEq returns false).

Lets dig into some examples to see how this works:

let mut count = use_signal(|| 1);
// double_count will rerun when state we read inside the memo changes (count)
let double_count = use_memo(move || count() * 2);

// memos act a lot like a read only version of a signal. You can read them, display them, and move them around like any other signal
println!("{}", double_count); // Prints "2"

// But you can't write to them directly
// Instead, any time you write to a value the memo reads, the memo will rerun
count += 1;

println!("{}", double_count); // Prints "4"

// Lets create another memo that reads the value of double_count
let double_count_plus_one = use_memo(move || double_count() + 1);

println!("{}", double_count_plus_one); // Prints "5"

// Now if we write to count the double_count memo will rerun
// If that the output of double_count changes, then it will cause double_count_plus_one to rerun
count += 1;

println!("{}", double_count); // Prints "6"
println!("{}", double_count_plus_one); // Prints "7"

// However if the value of double_count doesn't change after a write, then it won't trigger double_count_plus_one to rerun
// Since we just write the same value, the doubled value is still 6 and we don't rerun double_count_plus_one
*count.write() = 3;

println!("{}", double_count); // Prints "6"
println!("{}", double_count_plus_one); // Prints "7"

§With non-reactive dependencies

To add non-reactive dependencies, you can use the crate::use_reactive() hook.

Signals will automatically be added as dependencies, so you don’t need to call this method for them.

#[component]
fn Comp(count: u32) -> Element {
// Because the memo subscribes to `count` by adding it as a dependency, the memo will rerun every time `count` changes.
let new_count = use_memo(use_reactive((&count,), |(count,)| count + 1));
    todo!()
}

§Additional Information that may be useful

This function is a hook which means you need to follow the rules of hooks when you call it. You can click here to learn more about the rules of hooks.

Hooks in dioxus need to run in the same order every time you run the component. To make sure you run hooks in a consistent order, you should follow the rules of hooks:

  1. Hooks should only be called from the root of a component or another hook
fn App() -> Element {
    // ✅ You can call hooks from the body of a component
    let number = use_signal(|| 1);
    if number() == 1 {
        // ❌ You can run into issues if you can hooks inside other expressions inside your component
        // If number changes from 0 to 1, the order of the hooks will be different and your app may panic
        let string = use_signal(|| "hello world".to_string());
    }

    todo!()
}

fn use_my_hook() -> Signal<i32> {
    // ✅ You can call hooks from the body of other hooks
    let number = use_signal(|| 1);
    // ❌ Again, creating hooks inside expressions inside other hooks can cause issues
    if number() == 1 {
        let string = use_signal(|| "hello world".to_string());
    }

    number
}
  1. Hooks should always start with use_ to make it clear that you need to call them in a consistent order

Because hooks should only be called from the root of a component or another hook, you shouldn’t call hooks inside of:

  • ❌ Conditionals
fn App() -> Element {
    let number = use_signal(|| 1);
    // ❌ Changing the condition will change the order of the hooks
    if number() == 1 {
        let string = use_signal(|| "hello world".to_string());
    }

    // ❌ Changing the value you are matching will change the order of the hooks
    match number() {
        1 => {
            let string = use_signal(|| "hello world".to_string());
        },
        _ => (),
    }

    todo!()
}
  • ❌ Loops
fn App() -> Element {
    let number = use_signal(|| 1);
    // ❌ Changing the loop will change the order of the hooks
    for i in 0..number() {
        let string = use_signal(|| "hello world".to_string());
    }

    todo!()
}
  • ❌ Event Handlers
fn App() -> Element {
    rsx! {
        button {
            onclick: move |_| {
                // ❌ Calling the event handler will change the order of the hooks
                use_signal(|| "hello world".to_string());
            },
            "Click me"
        }
    }
}
  • ❌ Initialization closures in other hooks
fn App() -> Element {
    let number = use_signal(|| {
        // ❌ This closure will only be called when the component is first created. Running the component will change the order of the hooks
        let string = use_signal(|| "hello world".to_string());
        string()
    });

    todo!()
}
Why do hooks need to run in a consistent order?

Hooks need to be run in a consistent order because dioxus stores hooks in a list and uses the order you run hooks in to determine what part of the state belongs to which hook.

Lets look at an example component:

fn App() -> Element {
    let number = use_signal(|| 1); // Hook 1
    let string = use_signal(|| "hello world".to_string()); // Hook 2
    let doubled = use_memo(move || number() * 2); // Hook 3

    todo!()
}

When we first create the component, we run the hooks in the order they are defined and store the state in the component in a list.

[
    Box::new(1),
    Box::new("hello world".to_string()),
    Box::new(2),
]

Next time we run the component, we return items from the state list instead of creating state again.

[
    Box::new(1), // Hook 1 returns 1
    Box::new("hello world".to_string()), // Hook 2 returns "hello world"
    Box::new(2), // Hook 3 returns 2
]

The order the hooks are run it must be the same because the order determines which hook gets what state! If you run the hooks in a different order, dioxus may panic because it can’t turn the state back into the right type or you may just get the wrong state for your hook.

How should I move around state? (Click here to learn more about moving around and sharing state in Dioxus)

You will often need to move state around between your components. Dioxus provides three different ways to pass around state:

  1. Just pass your values as props:
fn MyComponent() -> Element {
    let count = use_signal(|| 0);

    rsx! {
        IncrementButton {
            count
        }
    }
}

#[component]
fn IncrementButton(mut count: Signal<i32>) -> Element {
    rsx! {
        button {
            onclick: move |_| count += 1,
            "Increment"
        }
    }
}

This is the most common way to pass state around. It is the most explicit and local to your component. Use this when it isn’t overly annoying to pass around a value.

  1. Use use_context to pass state from a parent component to all children:
#[derive(Clone, Copy)]
struct MyState {
    count: Signal<i32>
}

fn ParentComponent() -> Element {
    // Use context provider provides an unique type to all children of this component
    use_context_provider(|| MyState { count: Signal::new(0) });

    rsx! {
        // IncrementButton will have access to the count without explicitly passing it through props
        IncrementButton {}
    }
}

#[component]
fn IncrementButton() -> Element {
    // Use context gets the value from a parent component
    let mut count = use_context::<MyState>().count;

    rsx! {
        button {
            onclick: move |_| count += 1,
            "Increment"
        }
    }
}

This is slightly less explicit than passing it as a prop, but it is still local to the component. This is really great if you want state that is global to part of your app. It lets you create multiple global-ish states while still making state different when you reuse components. If I create a new ParentComponent, it will have a new MyState.

  1. Globals let you share state with your whole app with rust statics:
// Count will be created the first time you access it with the closure you pass to Signal::global
static COUNT: GlobalSignal<i32> = Signal::global(|| 0);

fn ParentComponent() -> Element {
    rsx! {
        IncrementButton {}
    }
}

fn IncrementButton() -> Element {
    rsx! {
        button {
            // You don't need to pass anything around or get anything out of the context because COUNT is global
            onclick: move |_| *COUNT.write() += 1,
            "Increment"
        }
    }
}

Global state can be very ergonomic if your state is truly global, but you shouldn’t use it if you need state to be different for different instances of your component. If I create another IncrementButton it will use the same COUNT. Libraries should generally avoid this to make components more reusable.

Note: Even though it is in a static, COUNT will be different for each app instance (this is generally only reliant on the server).