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
counterand mutates it bycounter.set(...). What's interesting is thatcounteris not declared as mutable. - Also
countergot cloned but.set(...)somehow mutates the reference to the originalcounterinhtml!{...}so the DOM will be rerendered whencountergets 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?