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
+19 -1
View File
@@ -5,7 +5,7 @@ use std::{
};
#[derive(Clone)]
pub struct HookEffect(Arc<Mutex<dyn Fn() + Send + Sync>>);
pub struct HookEffect(Arc<Mutex<dyn FnMut() + Send + Sync>>);
#[derive(Debug, Clone)]
pub struct State<T> {
@@ -101,3 +101,21 @@ impl<T> DerefMut for Inner<'_, T> {
&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());
}
}