A lightning fast state management module for Yew built with performance and simplicity as a first priority.
If you wish to separate the visual concerns and the business logic from your components, this library is made for you.
toml
[dependencies]
yewv = "0.1"
3 things need to be respected while using this library:
1. Only works with Yew functional components.
2. Store and service contexts must be registered in a parent or root component with ContextProvider
.
3. Store and service need to be used in a child component with use_store
/use_service
.
```rust // main.rs use yew::prelude::; use yewv::;
struct AppState { count: i32, }
fn app() -> Html {
let store = StoreContext::new(AppState { count: 0 });
html! {
fn counter() -> Html {
let store = usestore::
fn main() {
yew::start_app::
```rust use yew::prelude::; use yewv::;
struct AppState { count: i32, }
struct AppService {
store: StoreContext
impl AppService { fn incrementcount(&self) { let state = self.store.state(); self.store.setstate(AppState { count: state.count + 1, }); } }
fn app() -> Html {
let store = StoreContext::new(AppState { count: 0 });
let service = ServiceContext::new(AppService {
store: store.clone(),
});
html! {
fn counter() -> Html {
let service = useservice::
let count = store.map_ref(|state| &state.count);
let onclick = move |_| service.increment_count();
html! {
<button {onclick}>{format!("{} +", count)}</button>
}
}
fn main() {
yew::start_app::
If you only wish to reference a value owned by the store, you should use map_ref
.
As opposed to map
, map_ref
doesn't take ownership of the referenced value.
It is usually preferable to use map_ref
over map
when possible.
However, it is not always possible to use map_ref
. For instance, if the value you wish to access is not owned by the store state, you will need to use map
:
rust
let mapped = store.map(|state| state.some_vector.len());
The store utilizes highly optimized custom hooks for better performance and memory efficiency.
Subscriptions done to the store with map
, map_ref
and watch
will only trigger a render on the component if the observed value has changed.
Instead of propagating clone/copy of the application state throughout components, references are used.
When you are observing a value in the store, make sure you are not taking more than necessary. For instance, if you are only interested in a single value from a vector, there is no need to reference the entire vector:
rust
let mapped = store.map_ref(|state| &state.some_vector[0]);
let another = store.map_ref(|state| state.some_vector.iter().last().expect("to have a value"));
When and where it makes sense, try to break your monolithic stores into multiple. Doing so will improve the performance of the application as a whole.