-
-
Notifications
You must be signed in to change notification settings - Fork 726
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
use_memo
does not properly diff inputs and drops updates
#2416
Comments
Here is a smaller reproduction of the issue: #![allow(non_snake_case)]
use dioxus::prelude::*;
fn main() {
launch(app)
}
fn app() -> Element {
let mut count = use_signal(|| 0);
let memorized = use_memo(move || count());
let mut effect_run_count = use_hook(|| CopyValue::new(0));
// This effect should only run once, because the memo only ever reads as 1
use_effect(move || {
// trigger a sync update on memo. This will mark the effect as dirty
if *count.peek() == 0 {
count += 1
}
println!("{memorized}");
effect_run_count += 1;
assert!(effect_run_count() <= 1, "This effect should only run once");
});
rsx! { "hello world" }
}
We can fix this issue by unsubscribing to all signals before rerunning reactive scopes (use_memo, use_effect, use_resource, components). With that fix, the effect should not be subscribed to the memo until the effect is finished running which avoids the duplicate run (#2158) |
Why is recomputing the value necessary at that point? |
Memos use a push/pull based system to try to maintain consistent. They don't recompute until one of these two conditions is met:
let mut count = use_signal(|| 0);
// memorized will run once to get it's initial value
let memorized = use_memo(move || count() * 2);
// memorized is marked as dirty, but doesn't rerun - Lazily reruning lets us skip calculating the memo value when count = 1
count += 1;
// memorized is marked as dirty, but doesn't rerun
count += 1;
// memorized is read so it is rerun - this means we can never observe an out of date value
println!("{memorized}");
// memorized is marked as dirty, but doesn't rerun
count += 1;
// Once the component (and any parent components are done rendering, memorized is recomputed to see if any reactive closures/components need to be rerun) |
Interesting, thank you for elaborating. What happens if multiple observers read from the memo? I assume the value is recalculated on the first read, and the dirty flag is removed. The second read then gets the value without recalculating? |
Yes, exactly. It will rerun at most once for every write to a signal that is subscribes to |
Problem
Currently, when using
use_memo
, some updates are dropped, and some updates are identical to the previous one.Steps To Reproduce
See #2415 for reproduction test case and expected result.
I suspect this could be related to #2415 and #2370.
Questionnaire
The text was updated successfully, but these errors were encountered: