From 538cc8731f5a1d9af19e97805acd3e8d7d945340 Mon Sep 17 00:00:00 2001 From: Leo dev Date: Sun, 23 Nov 2025 11:23:28 +0100 Subject: [PATCH] Improved state mangement --- examples/hello_world.rs | 13 ++++++++++++- src/state.rs | 20 +++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/examples/hello_world.rs b/examples/hello_world.rs index 6efba6a..c21cbd5 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -30,6 +30,17 @@ fn main() { fn app(cx: &Arc) -> Vec { let count = use_state(0); + let count2 = use_state(0); + + use_effect( + { + let count2 = count2.clone(); + move || { + *count2.get() += 1; + } + }, + &[&count], + ); cx.on_event({ let count = count.clone(); @@ -40,5 +51,5 @@ fn app(cx: &Arc) -> Vec { } }); - vec![Node::String(Arc::new(move || format!("{count}")))] + vec![Node::String(Arc::new(move || format!("{count} {count2}")))] } diff --git a/src/state.rs b/src/state.rs index 49a21e9..c851b68 100644 --- a/src/state.rs +++ b/src/state.rs @@ -5,7 +5,7 @@ use std::{ }; #[derive(Clone)] -pub struct HookEffect(Arc>); +pub struct HookEffect(Arc>); #[derive(Debug, Clone)] pub struct State { @@ -101,3 +101,21 @@ impl DerefMut for Inner<'_, T> { &mut self.value } } + +pub trait HookDependency { + fn on_update(&self, hook: HookEffect); +} + +impl HookDependency for State { + fn on_update(&self, hook: HookEffect) { + self.dependents.lock().unwrap().push(hook); + } +} + +pub fn use_effect(f: F, dependencies: &[&dyn HookDependency]) { + let hook = HookEffect(Arc::new(Mutex::new(f))); + + for d in dependencies { + d.on_update(hook.clone()); + } +}