Improved state mangement

This commit is contained in:
2025-11-23 11:23:28 +01:00
parent b326fc48ed
commit 538cc8731f
2 changed files with 31 additions and 2 deletions
+12 -1
View File
@@ -30,6 +30,17 @@ fn main() {
fn app(cx: &Arc<Context>) -> Vec<Node> { fn app(cx: &Arc<Context>) -> Vec<Node> {
let count = use_state(0); let count = use_state(0);
let count2 = use_state(0);
use_effect(
{
let count2 = count2.clone();
move || {
*count2.get() += 1;
}
},
&[&count],
);
cx.on_event({ cx.on_event({
let count = count.clone(); let count = count.clone();
@@ -40,5 +51,5 @@ fn app(cx: &Arc<Context>) -> Vec<Node> {
} }
}); });
vec![Node::String(Arc::new(move || format!("{count}")))] vec![Node::String(Arc::new(move || format!("{count} {count2}")))]
} }
+19 -1
View File
@@ -5,7 +5,7 @@ use std::{
}; };
#[derive(Clone)] #[derive(Clone)]
pub struct HookEffect(Arc<Mutex<dyn Fn() + Send + Sync>>); pub struct HookEffect(Arc<Mutex<dyn FnMut() + Send + Sync>>);
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct State<T> { pub struct State<T> {
@@ -101,3 +101,21 @@ impl<T> DerefMut for Inner<'_, T> {
&mut self.value &mut self.value
} }
} }
pub trait HookDependency {
fn on_update(&self, hook: HookEffect);
}
impl<T> HookDependency for State<T> {
fn on_update(&self, hook: HookEffect) {
self.dependents.lock().unwrap().push(hook);
}
}
pub fn use_effect<F: FnMut() + Send + Sync + 'static>(f: F, dependencies: &[&dyn HookDependency]) {
let hook = HookEffect(Arc::new(Mutex::new(f)));
for d in dependencies {
d.on_update(hook.clone());
}
}