Are yew.rs hooks sound or unsound?

73 Views Asked by At

Yew (a ReactJs alternative for rust) has hooks that mimic those you can find in ReactJs.
I stumbled upon the following getting starter example where there's a counter and a button. If you press the button, the counter goes up by one:

#[function_component]
fn App() -> Html {
    let counter = use_state(|| 0);
    let onclick = {
        let counter = counter.clone();
        move |_| {
            let value = *counter + 1;
            counter.set(value);
        }
    };

    html! {
        <div>
            <button {onclick}>{ "+1" }</button>
            <p>{ *counter }</p>
        </div>
    }
}

(Code found here: https://yew.rs/docs/getting-started/build-a-sample-app)

Now I'm curious about the state/hook mechanic:

  • The onclick event handler clones counter and mutates it by counter.set(...). What's interesting is that counter is not declared as mutable.
  • Also counter got cloned but .set(...) somehow mutates the reference to the original counter in html!{...} so the DOM will be rerendered when counter gets updated.

While this is something we want, I can't figure out how this is compatible with rusts "only one mutable reference at a time" and that you shouldn't be able to mutate a variable that's declared as immutable.

Is there something I'm missing or did they implement it an "unsafe" way to feel more ReactJs like?

0

There are 0 best solutions below