From 506ccae049d81649fdda30c1da19864ffcd844b5 Mon Sep 17 00:00:00 2001 From: Leo dev Date: Mon, 26 Jan 2026 17:27:47 +0100 Subject: [PATCH] State syncing --- examples/hello_world.rs | 33 ++++----------------------------- src/state.rs | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 29 deletions(-) diff --git a/examples/hello_world.rs b/examples/hello_world.rs index dc2ccc3..09c9dd3 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -13,6 +13,9 @@ fn app(cx: &Arc) -> View { let count = use_state(0); let mount = use_mount_manual(); + // Sync state with children + use_sync_effect(cx, &count, |v| Count(v.clone()), &[&mount, &count]); + use_effect( { let count = count.clone(); @@ -29,18 +32,6 @@ fn app(cx: &Arc) -> View { &[&mount], ); - // Pass the count to the children - use_effect( - { - let count = count.clone(); - let cx = cx.clone(); - move || { - cx.emit_event(&Count(count.clone())); - } - }, - &[&mount], - ); - rsx! { // Static scope my_component (ctx, view) { @@ -67,25 +58,9 @@ fn app(cx: &Arc) -> View { } fn my_component(cx: &Arc) -> View { - let mount = use_mount(); + // Sync state with parent let count = use_sync_state(cx, 0, |Count(v)| v.get_dl()); - use_effect( - { - let count = count.clone(); - move || loop { - std::thread::sleep(std::time::Duration::from_millis(500)); - let mut count = count.get(); - if *count > 5 { - *count = 0; - continue; - } - *count += 1; - } - }, - &[&mount], - ); - rsx! { "Count: {count}" } diff --git a/src/state.rs b/src/state.rs index c8f2193..502e56c 100644 --- a/src/state.rs +++ b/src/state.rs @@ -189,3 +189,25 @@ pub fn use_sync_state< state } + +pub fn use_sync_effect< + T: Send + Sync + 'static, + Ev: 'static, + E: Fn(&State) -> Ev + Send + Sync + 'static, +>( + cx: &Arc, + state: &State, + encoder: E, + deps: &[&dyn HookDependency], +) { + use_effect( + { + let state = state.clone(); + let cx = cx.clone(); + move || { + cx.emit_event(&encoder(&state)); + } + }, + deps, + ); +}