Bounce
The uncomplicated state management library for Yew.
Bounce is inspired by Redux and Recoil.
Rationale
Yew state management solutions that are currently available all have some (or all) of the following limitations:
-
Too much boilerplate.
Users either have to manually control whether to notify subscribers or have to manually define contexts.
Changes should be detected automatically by
PartialEq
and not have to define contexts manually. -
State change notifies all.
State changes will notify all subscribers.
The
useSelector
hook forRedux
will only trigger a re-render when the selected value changes.If we were to create a state management library, it should also only notify the relevant subscribers.
-
Needless clones.
A clone of the state will be produced for all subscribers whenever there's a change.
Example
For bounce states to function, a <BounceRoot />
must be registered.
#[function_component(App)]
fn app() -> Html {
html! {
<BounceRoot>
{children}
</BounceRoot>
}
}
A simple state is called an Atom
.
You can derive Atom
for any struct that implements PartialEq
and Default
.
#[derive(PartialEq, Atom)]
struct Username {
inner: String,
}
impl Default for Username {
fn default() -> Self {
Self {
inner: "Jane Doe".into(),
}
}
}
You can then use it with the use_atom
hook.
When an Atom
is first used, it will be initialised with it's Default
value.
#[function_component(Setter)]
fn setter() -> Html {
let username = use_atom::<Username>();
let on_text_input = {
let username = username.clone();
Callback::from(move |e: InputEvent| {
let input: HtmlInputElement = e.target_unchecked_into();
username.set(Username { inner: input.value().into() });
})
};
html! {
<div>
<input type_="text" oninput={on_text_input} value={username.inner.to_string()} />
</div>
}
}
If you wish to create a read-only (or set-only) handle, you can use use_atom_value
(or use_atom_setter
).
#[function_component(Reader)]
fn reader() -> Html {
let username = use_atom_value::<Username>();
html! { <div>{"Hello, "}{&username.inner}</div> }
}
That's it!
You can find the full example here.
License
Bounce is dual licensed under the MIT license and the Apache License (Version 2.0).