yew: Regression: elements are re-rendered even if they didn't change, when there's a list below them (worked in v0.19.3)
Problem
Elements are re-rendered even if they didn’t change, when there’s a list below them. It works correctly in yew 0.19.3, but no longer in yew 0.20.0.
This is especially problematic when the re-rendered element is e.g. a <video> since when it gets re-rendered it stops and resets to the beginning. This is currently blocking me from updating 0.19.3 -> 0.20.0
Steps To Reproduce
- Have a component that renders an element and a dynamic list below it
- Change the list to cause a re-render of the component
- The elements coming from the list get rendered, but so does the other element too (this can be easily seen in the chrome devtools since you can see the element flash when it changes)
Run/see the full repro in this repo: https://github.com/andoalon/yew-bug (just run trunk serve --open)
In short, it boils down to this:
#[function_component(Video)]
pub fn video() -> Html {
let number = use_state_eq(|| None::<i64>);
let time_update = {
let number = number.clone();
Callback::from(move |event| {
// number_from_video() returns some number
// based on the video's current position
number.set(number_from_video(event));
})
};
let number_vec = {
if let Some(num) = *number {
vec![html! {
<button class="my-button">
{format!("Number: {num}")}
</button>
}]
} else {
Vec::new()
}
};
let number_opt = number.map(|num| html! {
<button class="my-button">
{format!("Number: {num}")}
</button>
});
html! {
<>
// The video element gets re-rendered when the list below changes
// in cases 2, 2.1, 3 and 3.1 (it does not in case 1). It also doesn't get
// re-rendered in yew 0.19.3
<video muted=true controls=true type={VIDEO_TYPE} src={VIDEO_URL}
ontimeupdate={time_update}>
</video>
// Case 1: Works
// if let Some(num) = *number {
// <button class="my-button">
// {format!("Number: {num}")}
// </button>
// }
{ number_vec } // Case 2: Bug
//{ for number_vec } // Case 2.1: Bug
//{ number_opt } // Case 3: Bug
//{ for number_opt } // Case 3.1: Bug
</>
}
}
Expected behavior Elements are only re-rendered if they changed.
Observed behavior with <video>
It resets to the beginning and stops when the list below it changes. On a different note, I noticed that the muted attribute of <video> seems to not be working. Not sure if I misused it 🤔
Environment:
- Yew version:
v0.20.0(previously was usingv0.19.3where the issue was not present) - Rust version:
1.69.0(stable) - Target, if relevant:
wasm32-unknown-unknown(not sure if relevant) - Build tool, if relevant:
trunk(not sure if relevant) - OS, if relevant: Windows 10 (not sure if relevant)
- Browser and version, if relevant: reproduced in Chrome 112.0.5615.138 (Official Build) (64-bit) and Firefox 112.0.2 (64-bit)
Questionnaire
- I’m interested in fixing this myself but don’t know where to start
- I would like to fix and I have a solution
- I don’t have time to fix this right now, but maybe later
About this issue
- Original URL
- State: open
- Created 4 years ago
- Comments: 17 (13 by maintainers)
Commits related to this issue
- Fix input rerender See https://github.com/yewstack/yew/issues/3262 — committed to bngo92/mybops by bngo92 3 years ago
Sorry about the delay. I finally have some time to sit down and explain my opinion on this issue.
In short, I do not think expanding
{for expr}into the parentVListis a desirable behaviour. In my opinion, allhtml!declared elements, components and expressions ({for expr}itself should be keyless-safe, but items expanded by expr isn’t.) should be keyless-safe, which includes this issue.My main concern of the current
{for expr}behaviour, is that this can render previously keyless-safe VList / Children key-required, by simply inserting{for expr}into somewhere of anhtml!, leading to confusing, hard to debug scenarios.However, this is not the only concern around this extending behaviour. So I will discuss this in detail:
1. An extending for-expression is hard to spot, and hard to maintain.
Expanding
{for expr}into the parent VList, renders all adjacent elements defined byhtml!key-required.Whilst we can make a distinction between
{contents}and{for contents}I think due to limitations of Rust, we cannot make{contents}to implement for any type that is an iterator, the blank implementation is already implemented forstd::fmt::Display. This leaves user with an iterator content with no choice but to use{for contents}as that is more intuitive (and efficient?) to do than.collect::<Vec<_>>().The above, which increased the likelihood of users using
{for contents}, combined with{for expr}'s side effect could lead users into tedious debugging scenarios.Suppose that a developer has created the following page:
By including
{for seasonal_contents}and{for random_3_questions}, all child nodes of<main />and<form />are now key-required.The developer of this page, is finding that the contents are not updating as expected that contents are getting resetted from time to time, and is trying to debug this page.
This creates some questions for the debugging process:
{for expr}is the issue here and it is rendering its siblings as key-required?In addition, this is not only a concern of when one is working on their own code, but also when reviewing other people’s code when adding a
{for expr}looks like a small change so the reviewer usually do not expand the code and think it very deeply before moving on to other parts of the PR.2. What key should a
VNodeuse?If we assume that the first point isn’t an issue, this developer is willing to deal with it, expanding into the same VList still has another issue that can very easily forfeit the user’s effort of trying to key elements.
Let’s assume that we have a component named
Parent:The author knows that if an for-expression is used, they need to key all the sibling elements as well. So they keyed the header element. As it is fully keyed,
Childrenof theParentcomponent should reconcile as expected, given we have a way to enforceChildrento be fully keyed. The author then published theParentcomponent as a crate tocrates.io.A couple days later, a user created an
Appcomponent usingParent. The user also knows that they have to key all elements if an for-expression is used so they keyed their app header.Despite both sides have taken precaution to make sure that all items are keyed, the application still doesn’t work properly. The effort of both sides are nullified because they both used
headeras the key.In this case, would it be reasonable to assume that it’s the responsibility of the author of
Parentto exhaustively list the keys they are using and the creator ofAppshould read the fine manual of the parent component?3. It’s very unintuitive to key certain expressions.
If a VList not fully-keyed, the behaviour is equivalent to unkeyed. So it’s important to key every child node in a VList. By adding
{for expr}, all siblings are required to be keyed.However, certain expressions are very unintuitive to key. This is OK as currently as I would assume that they are never designed to be keyed (nor needed if used in
html!).For the following
html!,It might be easy to assume that it should be keyed as following:
However, this does not cover the default value of this expression as it is
VNode::default(), so it actually needs to be keyed in the following way by adding a fragment:The extreme (yet common) scenario would be that we need to key text nodes.
I think this is not only hard to justify, but also beyond the effort that most people is willing to spend on a feature.
4. Conclusion
In my opinion, keys should only be required in the following scenarios:
Inside of html created by
Vec/Iterator.Components’ keyless-safety should not be impacted by anything else declared in
html!. (Or else we should make aunsafe {}clause for expressions that could impact it this way.)When a component needs to be forcibly replaced,
i.e.: a different key for the same tag / component forces a destroy and create cycle, instead of reusing the existing component / tag.
I think the behaviour described by @dylanowen is also more desirable, which we should consider.
I personally think this limits scenarios where keys are required, makes key requirement easier to remember and is more difficult to get confused of when do you need to use it.
The reality is, even with React’s easier key requirement and warnings in developer console, it is still not uncommon to see React code that misuse / forget keys.
I certainly wish that we do not make the key requirement more complicated and subtle (1), making coming up keys itself more difficult (2), or make users life harder (3).
In addition, the only reason why
{for expr}should be expanded to current VList I can come up with is because we want to manipulateChildrenin which itself doesn’t work properly for reasons I described in #3256.I believe this has not been fixed.
{fox x}is still problamatic and needs aVListto help with that.A falsy value for
ain React, renders nothing in the DOM, but still evaluate tofalsewhen you construct the React’s children. This always result in a slot being reserved even if the element is not rendered. When you try to force it to happen with arrays manually, React will emit a warning to the developer console stating that keys are required in these situations.The JSX expression is more equivalent to:
That’s why declarative syntax is safe without keys where arrays and iterators isn’t as in a JSX expression / HTML macro, the declared block can always indicate there is an expression regardless of whether it is rendered.